1
0

ShareByMailProvider.php 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  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->addBodyButton(
  319. $this->l->t('Open %s', [$filename]),
  320. $link
  321. );
  322. // If multiple recipients are given, we send the mail to all of them
  323. if (count($emails) > 1) {
  324. // We do not want to expose the email addresses of the other recipients
  325. $message->setBcc($emails);
  326. } else {
  327. $message->setTo($emails);
  328. }
  329. // The "From" contains the sharers name
  330. $instanceName = $this->defaults->getName();
  331. $senderName = $instanceName;
  332. if ($this->settingsManager->replyToInitiator()) {
  333. $senderName = $this->l->t(
  334. '%1$s via %2$s',
  335. [
  336. $initiatorDisplayName,
  337. $instanceName
  338. ]
  339. );
  340. }
  341. $message->setFrom([Util::getDefaultEmailAddress($instanceName) => $senderName]);
  342. // The "Reply-To" is set to the sharer if an mail address is configured
  343. // also the default footer contains a "Do not reply" which needs to be adjusted.
  344. if ($initiatorUser && $this->settingsManager->replyToInitiator()) {
  345. $initiatorEmail = $initiatorUser->getEMailAddress();
  346. if ($initiatorEmail !== null) {
  347. $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
  348. $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
  349. } else {
  350. $emailTemplate->addFooter();
  351. }
  352. } else {
  353. $emailTemplate->addFooter();
  354. }
  355. $message->useTemplate($emailTemplate);
  356. $failedRecipients = $this->mailer->send($message);
  357. if (!empty($failedRecipients)) {
  358. $this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients));
  359. return;
  360. }
  361. }
  362. /**
  363. * Send password to recipient of a mail share
  364. * Will return false if
  365. * 1. the password is empty
  366. * 2. the setting to send the password by mail is disabled
  367. * 3. the share is set to send the password by talk
  368. *
  369. * @param IShare $share
  370. * @param string $password
  371. * @param array $emails
  372. * @return bool
  373. */
  374. protected function sendPassword(IShare $share, string $password, array $emails): bool {
  375. $filename = $share->getNode()->getName();
  376. $initiator = $share->getSharedBy();
  377. $shareWith = $share->getSharedWith();
  378. if ($password === '' || $this->settingsManager->sendPasswordByMail() === false || $share->getSendPasswordByTalk()) {
  379. return false;
  380. }
  381. $initiatorUser = $this->userManager->get($initiator);
  382. $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
  383. $initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
  384. $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]);
  385. $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]);
  386. $message = $this->mailer->createMessage();
  387. $emailTemplate = $this->mailer->createEMailTemplate('sharebymail.RecipientPasswordNotification', [
  388. 'filename' => $filename,
  389. 'password' => $password,
  390. 'initiator' => $initiatorDisplayName,
  391. 'initiatorEmail' => $initiatorEmailAddress,
  392. 'shareWith' => $shareWith,
  393. ]);
  394. $emailTemplate->setSubject($this->l->t('Password to access %1$s shared to you by %2$s', [$filename, $initiatorDisplayName]));
  395. $emailTemplate->addHeader();
  396. $emailTemplate->addHeading($this->l->t('Password to access %s', [$filename]), false);
  397. $emailTemplate->addBodyText(htmlspecialchars($htmlBodyPart), $plainBodyPart);
  398. $emailTemplate->addBodyText($this->l->t('It is protected with the following password:'));
  399. $emailTemplate->addBodyText($password);
  400. if ($this->config->getSystemValue('sharing.enable_mail_link_password_expiration', false) === true) {
  401. $expirationTime = new \DateTime();
  402. $expirationInterval = $this->config->getSystemValue('sharing.mail_link_password_expiration_interval', 3600);
  403. $expirationTime = $expirationTime->add(new \DateInterval('PT' . $expirationInterval . 'S'));
  404. $emailTemplate->addBodyText($this->l->t('This password will expire at %s', [$expirationTime->format('r')]));
  405. }
  406. // If multiple recipients are given, we send the mail to all of them
  407. if (count($emails) > 1) {
  408. // We do not want to expose the email addresses of the other recipients
  409. $message->setBcc($emails);
  410. } else {
  411. $message->setTo($emails);
  412. }
  413. // The "From" contains the sharers name
  414. $instanceName = $this->defaults->getName();
  415. $senderName = $instanceName;
  416. if ($this->settingsManager->replyToInitiator()) {
  417. $senderName = $this->l->t(
  418. '%1$s via %2$s',
  419. [
  420. $initiatorDisplayName,
  421. $instanceName
  422. ]
  423. );
  424. }
  425. $message->setFrom([Util::getDefaultEmailAddress($instanceName) => $senderName]);
  426. // The "Reply-To" is set to the sharer if an mail address is configured
  427. // also the default footer contains a "Do not reply" which needs to be adjusted.
  428. if ($initiatorUser && $this->settingsManager->replyToInitiator()) {
  429. $initiatorEmail = $initiatorUser->getEMailAddress();
  430. if ($initiatorEmail !== null) {
  431. $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
  432. $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
  433. } else {
  434. $emailTemplate->addFooter();
  435. }
  436. } else {
  437. $emailTemplate->addFooter();
  438. }
  439. $message->useTemplate($emailTemplate);
  440. $failedRecipients = $this->mailer->send($message);
  441. if (!empty($failedRecipients)) {
  442. $this->logger->error('Share password mail could not be sent to: ' . implode(', ', $failedRecipients));
  443. return false;
  444. }
  445. $this->createPasswordSendActivity($share, $shareWith, false);
  446. return true;
  447. }
  448. protected function sendNote(IShare $share): void {
  449. $recipient = $share->getSharedWith();
  450. $filename = $share->getNode()->getName();
  451. $initiator = $share->getSharedBy();
  452. $note = $share->getNote();
  453. $initiatorUser = $this->userManager->get($initiator);
  454. $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
  455. $initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
  456. $plainHeading = $this->l->t('%1$s shared %2$s with you and wants to add:', [$initiatorDisplayName, $filename]);
  457. $htmlHeading = $this->l->t('%1$s shared %2$s with you and wants to add', [$initiatorDisplayName, $filename]);
  458. $message = $this->mailer->createMessage();
  459. $emailTemplate = $this->mailer->createEMailTemplate('shareByMail.sendNote');
  460. $emailTemplate->setSubject($this->l->t('%s added a note to a file shared with you', [$initiatorDisplayName]));
  461. $emailTemplate->addHeader();
  462. $emailTemplate->addHeading(htmlspecialchars($htmlHeading), $plainHeading);
  463. $emailTemplate->addBodyText(htmlspecialchars($note), $note);
  464. $link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
  465. ['token' => $share->getToken()]);
  466. $emailTemplate->addBodyButton(
  467. $this->l->t('Open %s', [$filename]),
  468. $link
  469. );
  470. // The "From" contains the sharers name
  471. $instanceName = $this->defaults->getName();
  472. $senderName = $instanceName;
  473. if ($this->settingsManager->replyToInitiator()) {
  474. $senderName = $this->l->t(
  475. '%1$s via %2$s',
  476. [
  477. $initiatorDisplayName,
  478. $instanceName
  479. ]
  480. );
  481. }
  482. $message->setFrom([Util::getDefaultEmailAddress($instanceName) => $senderName]);
  483. if ($this->settingsManager->replyToInitiator() && $initiatorEmailAddress !== null) {
  484. $message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
  485. $emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
  486. } else {
  487. $emailTemplate->addFooter();
  488. }
  489. $message->setTo([$recipient]);
  490. $message->useTemplate($emailTemplate);
  491. $this->mailer->send($message);
  492. }
  493. /**
  494. * send auto generated password to the owner. This happens if the admin enforces
  495. * a password for mail shares and forbid to send the password by mail to the recipient
  496. *
  497. * @throws \Exception
  498. */
  499. protected function sendPasswordToOwner(IShare $share, string $password): bool {
  500. $filename = $share->getNode()->getName();
  501. $initiator = $this->userManager->get($share->getSharedBy());
  502. $initiatorEMailAddress = ($initiator instanceof IUser) ? $initiator->getEMailAddress() : null;
  503. $initiatorDisplayName = ($initiator instanceof IUser) ? $initiator->getDisplayName() : $share->getSharedBy();
  504. $shareWith = $share->getSharedWith();
  505. if ($initiatorEMailAddress === null) {
  506. throw new \Exception(
  507. $this->l->t('We cannot send you the auto-generated password. Please set a valid email address in your personal settings and try again.')
  508. );
  509. }
  510. $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()]);
  511. $message = $this->mailer->createMessage();
  512. $emailTemplate = $this->mailer->createEMailTemplate('sharebymail.OwnerPasswordNotification', [
  513. 'filename' => $filename,
  514. 'password' => $password,
  515. 'initiator' => $initiatorDisplayName,
  516. 'initiatorEmail' => $initiatorEMailAddress,
  517. 'shareWith' => $shareWith,
  518. ]);
  519. $emailTemplate->setSubject($this->l->t('Password to access %1$s shared by you with %2$s', [$filename, $shareWith]));
  520. $emailTemplate->addHeader();
  521. $emailTemplate->addHeading($this->l->t('Password to access %s', [$filename]), false);
  522. $emailTemplate->addBodyText($bodyPart);
  523. $emailTemplate->addBodyText($this->l->t('This is the password:'));
  524. $emailTemplate->addBodyText($password);
  525. if ($this->config->getSystemValue('sharing.enable_mail_link_password_expiration', false) === true) {
  526. $expirationTime = new \DateTime();
  527. $expirationInterval = $this->config->getSystemValue('sharing.mail_link_password_expiration_interval', 3600);
  528. $expirationTime = $expirationTime->add(new \DateInterval('PT' . $expirationInterval . 'S'));
  529. $emailTemplate->addBodyText($this->l->t('This password will expire at %s', [$expirationTime->format('r')]));
  530. }
  531. $emailTemplate->addBodyText($this->l->t('You can choose a different password at any time in the share dialog.'));
  532. $emailTemplate->addFooter();
  533. $instanceName = $this->defaults->getName();
  534. $senderName = $this->l->t(
  535. '%1$s via %2$s',
  536. [
  537. $initiatorDisplayName,
  538. $instanceName
  539. ]
  540. );
  541. $message->setFrom([Util::getDefaultEmailAddress($instanceName) => $senderName]);
  542. $message->setTo([$initiatorEMailAddress => $initiatorDisplayName]);
  543. $message->useTemplate($emailTemplate);
  544. $this->mailer->send($message);
  545. $this->createPasswordSendActivity($share, $shareWith, true);
  546. return true;
  547. }
  548. private function getAbsoluteImagePath(string $path):string {
  549. return $this->urlGenerator->getAbsoluteURL(
  550. $this->urlGenerator->imagePath('core', $path)
  551. );
  552. }
  553. /**
  554. * generate share token
  555. */
  556. protected function generateToken(int $size = 15): string {
  557. $token = $this->secureRandom->generate($size, ISecureRandom::CHAR_HUMAN_READABLE);
  558. return $token;
  559. }
  560. /**
  561. * Get all children of this share
  562. *
  563. * @return IShare[]
  564. */
  565. public function getChildren(IShare $parent): array {
  566. $children = [];
  567. $qb = $this->dbConnection->getQueryBuilder();
  568. $qb->select('*')
  569. ->from('share')
  570. ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
  571. ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)))
  572. ->orderBy('id');
  573. $cursor = $qb->executeQuery();
  574. while ($data = $cursor->fetch()) {
  575. $children[] = $this->createShareObject($data);
  576. }
  577. $cursor->closeCursor();
  578. return $children;
  579. }
  580. /**
  581. * Add share to the database and return the ID
  582. */
  583. protected function addShareToDB(
  584. ?int $itemSource,
  585. ?string $itemType,
  586. ?string $shareWith,
  587. ?string $sharedBy,
  588. ?string $uidOwner,
  589. ?int $permissions,
  590. ?string $token,
  591. ?string $password,
  592. ?\DateTimeInterface $passwordExpirationTime,
  593. ?bool $sendPasswordByTalk,
  594. ?bool $hideDownload,
  595. ?string $label,
  596. ?\DateTimeInterface $expirationTime,
  597. ?string $note = '',
  598. ?IAttributes $attributes = null,
  599. ?bool $mailSend = true,
  600. ): int {
  601. $qb = $this->dbConnection->getQueryBuilder();
  602. $qb->insert('share')
  603. ->setValue('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL))
  604. ->setValue('item_type', $qb->createNamedParameter($itemType))
  605. ->setValue('item_source', $qb->createNamedParameter($itemSource))
  606. ->setValue('file_source', $qb->createNamedParameter($itemSource))
  607. ->setValue('share_with', $qb->createNamedParameter($shareWith))
  608. ->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
  609. ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
  610. ->setValue('permissions', $qb->createNamedParameter($permissions))
  611. ->setValue('token', $qb->createNamedParameter($token))
  612. ->setValue('password', $qb->createNamedParameter($password))
  613. ->setValue('password_expiration_time', $qb->createNamedParameter($passwordExpirationTime, IQueryBuilder::PARAM_DATETIME_MUTABLE))
  614. ->setValue('password_by_talk', $qb->createNamedParameter($sendPasswordByTalk, IQueryBuilder::PARAM_BOOL))
  615. ->setValue('stime', $qb->createNamedParameter(time()))
  616. ->setValue('hide_download', $qb->createNamedParameter((int)$hideDownload, IQueryBuilder::PARAM_INT))
  617. ->setValue('label', $qb->createNamedParameter($label))
  618. ->setValue('note', $qb->createNamedParameter($note))
  619. ->setValue('mail_send', $qb->createNamedParameter((int)$mailSend, IQueryBuilder::PARAM_INT));
  620. // set share attributes
  621. $shareAttributes = $this->formatShareAttributes($attributes);
  622. $qb->setValue('attributes', $qb->createNamedParameter($shareAttributes));
  623. if ($expirationTime !== null) {
  624. $qb->setValue('expiration', $qb->createNamedParameter($expirationTime, IQueryBuilder::PARAM_DATETIME_MUTABLE));
  625. }
  626. $qb->executeStatement();
  627. return $qb->getLastInsertId();
  628. }
  629. /**
  630. * Update a share
  631. */
  632. public function update(IShare $share, ?string $plainTextPassword = null): IShare {
  633. $originalShare = $this->getShareById($share->getId());
  634. // a real password was given
  635. $validPassword = $plainTextPassword !== null && $plainTextPassword !== '';
  636. if ($validPassword && ($originalShare->getPassword() !== $share->getPassword() ||
  637. ($originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk()))) {
  638. $emails = $this->getSharedWithEmails($share);
  639. $validEmails = array_filter($emails, function ($email) {
  640. return $this->mailer->validateMailAddress($email);
  641. });
  642. $this->sendPassword($share, $plainTextPassword, $validEmails);
  643. }
  644. $shareAttributes = $this->formatShareAttributes($share->getAttributes());
  645. /*
  646. * We allow updating mail shares
  647. */
  648. $qb = $this->dbConnection->getQueryBuilder();
  649. $qb->update('share')
  650. ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
  651. ->set('item_source', $qb->createNamedParameter($share->getNodeId()))
  652. ->set('file_source', $qb->createNamedParameter($share->getNodeId()))
  653. ->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
  654. ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
  655. ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
  656. ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
  657. ->set('password', $qb->createNamedParameter($share->getPassword()))
  658. ->set('password_expiration_time', $qb->createNamedParameter($share->getPasswordExpirationTime(), IQueryBuilder::PARAM_DATETIME_MUTABLE))
  659. ->set('label', $qb->createNamedParameter($share->getLabel()))
  660. ->set('password_by_talk', $qb->createNamedParameter($share->getSendPasswordByTalk(), IQueryBuilder::PARAM_BOOL))
  661. ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATETIME_MUTABLE))
  662. ->set('note', $qb->createNamedParameter($share->getNote()))
  663. ->set('hide_download', $qb->createNamedParameter((int)$share->getHideDownload(), IQueryBuilder::PARAM_INT))
  664. ->set('attributes', $qb->createNamedParameter($shareAttributes))
  665. ->set('mail_send', $qb->createNamedParameter((int)$share->getMailSend(), IQueryBuilder::PARAM_INT))
  666. ->set('reminder_sent', $qb->createNamedParameter($share->getReminderSent(), IQueryBuilder::PARAM_BOOL))
  667. ->executeStatement();
  668. if ($originalShare->getNote() !== $share->getNote() && $share->getNote() !== '') {
  669. $this->sendNote($share);
  670. }
  671. return $share;
  672. }
  673. /**
  674. * @inheritdoc
  675. */
  676. public function move(IShare $share, $recipient): IShare {
  677. /**
  678. * nothing to do here, mail shares are only outgoing shares
  679. */
  680. return $share;
  681. }
  682. /**
  683. * Delete a share (owner unShares the file)
  684. *
  685. * @param IShare $share
  686. */
  687. public function delete(IShare $share): void {
  688. try {
  689. $this->createShareActivity($share, 'unshare');
  690. } catch (\Exception $e) {
  691. }
  692. $this->removeShareFromTable((int)$share->getId());
  693. }
  694. /**
  695. * @inheritdoc
  696. */
  697. public function deleteFromSelf(IShare $share, $recipient): void {
  698. // nothing to do here, mail shares are only outgoing shares
  699. }
  700. public function restore(IShare $share, string $recipient): IShare {
  701. throw new GenericShareException('not implemented');
  702. }
  703. /**
  704. * @inheritdoc
  705. */
  706. public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset): array {
  707. $qb = $this->dbConnection->getQueryBuilder();
  708. $qb->select('*')
  709. ->from('share');
  710. $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)));
  711. /**
  712. * Reshares for this user are shares where they are the owner.
  713. */
  714. if ($reshares === false) {
  715. //Special case for old shares created via the web UI
  716. $or1 = $qb->expr()->andX(
  717. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
  718. $qb->expr()->isNull('uid_initiator')
  719. );
  720. $qb->andWhere(
  721. $qb->expr()->orX(
  722. $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
  723. $or1
  724. )
  725. );
  726. } elseif ($node === null) {
  727. $qb->andWhere(
  728. $qb->expr()->orX(
  729. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
  730. $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
  731. )
  732. );
  733. }
  734. if ($node !== null) {
  735. $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
  736. }
  737. if ($limit !== -1) {
  738. $qb->setMaxResults($limit);
  739. }
  740. $qb->setFirstResult($offset);
  741. $qb->orderBy('id');
  742. $cursor = $qb->executeQuery();
  743. $shares = [];
  744. while ($data = $cursor->fetch()) {
  745. $shares[] = $this->createShareObject($data);
  746. }
  747. $cursor->closeCursor();
  748. return $shares;
  749. }
  750. /**
  751. * @inheritdoc
  752. */
  753. public function getShareById($id, $recipientId = null): IShare {
  754. $qb = $this->dbConnection->getQueryBuilder();
  755. $qb->select('*')
  756. ->from('share')
  757. ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
  758. ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)));
  759. $cursor = $qb->executeQuery();
  760. $data = $cursor->fetch();
  761. $cursor->closeCursor();
  762. if ($data === false) {
  763. throw new ShareNotFound();
  764. }
  765. try {
  766. $share = $this->createShareObject($data);
  767. } catch (InvalidShare $e) {
  768. throw new ShareNotFound();
  769. }
  770. return $share;
  771. }
  772. /**
  773. * Get shares for a given path
  774. *
  775. * @return IShare[]
  776. */
  777. public function getSharesByPath(Node $path): array {
  778. $qb = $this->dbConnection->getQueryBuilder();
  779. $cursor = $qb->select('*')
  780. ->from('share')
  781. ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
  782. ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)))
  783. ->executeQuery();
  784. $shares = [];
  785. while ($data = $cursor->fetch()) {
  786. $shares[] = $this->createShareObject($data);
  787. }
  788. $cursor->closeCursor();
  789. return $shares;
  790. }
  791. /**
  792. * @inheritdoc
  793. */
  794. public function getSharedWith($userId, $shareType, $node, $limit, $offset): array {
  795. /** @var IShare[] $shares */
  796. $shares = [];
  797. //Get shares directly with this user
  798. $qb = $this->dbConnection->getQueryBuilder();
  799. $qb->select('*')
  800. ->from('share');
  801. // Order by id
  802. $qb->orderBy('id');
  803. // Set limit and offset
  804. if ($limit !== -1) {
  805. $qb->setMaxResults($limit);
  806. }
  807. $qb->setFirstResult($offset);
  808. $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)));
  809. $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
  810. // Filter by node if provided
  811. if ($node !== null) {
  812. $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
  813. }
  814. $cursor = $qb->executeQuery();
  815. while ($data = $cursor->fetch()) {
  816. $shares[] = $this->createShareObject($data);
  817. }
  818. $cursor->closeCursor();
  819. return $shares;
  820. }
  821. /**
  822. * Get a share by token
  823. *
  824. * @throws ShareNotFound
  825. */
  826. public function getShareByToken($token): IShare {
  827. $qb = $this->dbConnection->getQueryBuilder();
  828. $cursor = $qb->select('*')
  829. ->from('share')
  830. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)))
  831. ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
  832. ->executeQuery();
  833. $data = $cursor->fetch();
  834. if ($data === false) {
  835. throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
  836. }
  837. try {
  838. $share = $this->createShareObject($data);
  839. } catch (InvalidShare $e) {
  840. throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
  841. }
  842. return $share;
  843. }
  844. /**
  845. * remove share from table
  846. */
  847. protected function removeShareFromTable(int $shareId): void {
  848. $qb = $this->dbConnection->getQueryBuilder();
  849. $qb->delete('share')
  850. ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
  851. $qb->executeStatement();
  852. }
  853. /**
  854. * Create a share object from a database row
  855. *
  856. * @throws InvalidShare
  857. * @throws ShareNotFound
  858. */
  859. protected function createShareObject(array $data): IShare {
  860. $share = new Share($this->rootFolder, $this->userManager);
  861. $share->setId((int)$data['id'])
  862. ->setShareType((int)$data['share_type'])
  863. ->setPermissions((int)$data['permissions'])
  864. ->setTarget($data['file_target'])
  865. ->setMailSend((bool)$data['mail_send'])
  866. ->setNote($data['note'])
  867. ->setToken($data['token']);
  868. $shareTime = new \DateTime();
  869. $shareTime->setTimestamp((int)$data['stime']);
  870. $share->setShareTime($shareTime);
  871. $share->setSharedWith($data['share_with'] ?? '');
  872. $share->setPassword($data['password']);
  873. $passwordExpirationTime = \DateTime::createFromFormat('Y-m-d H:i:s', $data['password_expiration_time'] ?? '');
  874. $share->setPasswordExpirationTime($passwordExpirationTime !== false ? $passwordExpirationTime : null);
  875. $share->setLabel($data['label']);
  876. $share->setSendPasswordByTalk((bool)$data['password_by_talk']);
  877. $share->setHideDownload((bool)$data['hide_download']);
  878. $share->setReminderSent((bool)$data['reminder_sent']);
  879. if ($data['uid_initiator'] !== null) {
  880. $share->setShareOwner($data['uid_owner']);
  881. $share->setSharedBy($data['uid_initiator']);
  882. } else {
  883. //OLD SHARE
  884. $share->setSharedBy($data['uid_owner']);
  885. $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
  886. $owner = $path->getOwner();
  887. $share->setShareOwner($owner->getUID());
  888. }
  889. if ($data['expiration'] !== null) {
  890. $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
  891. if ($expiration !== false) {
  892. $share->setExpirationDate($expiration);
  893. }
  894. }
  895. $share = $this->updateShareAttributes($share, $data['attributes']);
  896. $share->setNodeId((int)$data['file_source']);
  897. $share->setNodeType($data['item_type']);
  898. $share->setProviderId($this->identifier());
  899. return $share;
  900. }
  901. /**
  902. * Get the node with file $id for $user
  903. *
  904. * @throws InvalidShare
  905. */
  906. private function getNode(string $userId, int $id): Node {
  907. try {
  908. $userFolder = $this->rootFolder->getUserFolder($userId);
  909. } catch (NoUserException $e) {
  910. throw new InvalidShare();
  911. }
  912. $nodes = $userFolder->getById($id);
  913. if (empty($nodes)) {
  914. throw new InvalidShare();
  915. }
  916. return $nodes[0];
  917. }
  918. /**
  919. * A user is deleted from the system
  920. * So clean up the relevant shares.
  921. */
  922. public function userDeleted($uid, $shareType): void {
  923. $qb = $this->dbConnection->getQueryBuilder();
  924. $qb->delete('share')
  925. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)))
  926. ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
  927. ->executeStatement();
  928. }
  929. /**
  930. * This provider does not support group shares
  931. */
  932. public function groupDeleted($gid): void {
  933. }
  934. /**
  935. * This provider does not support group shares
  936. */
  937. public function userDeletedFromGroup($uid, $gid): void {
  938. }
  939. /**
  940. * get database row of a give share
  941. *
  942. * @throws ShareNotFound
  943. */
  944. protected function getRawShare(int $id): array {
  945. // Now fetch the inserted share and create a complete share object
  946. $qb = $this->dbConnection->getQueryBuilder();
  947. $qb->select('*')
  948. ->from('share')
  949. ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
  950. $cursor = $qb->executeQuery();
  951. $data = $cursor->fetch();
  952. $cursor->closeCursor();
  953. if ($data === false) {
  954. throw new ShareNotFound;
  955. }
  956. return $data;
  957. }
  958. public function getSharesInFolder($userId, Folder $node, $reshares, $shallow = true): array {
  959. $qb = $this->dbConnection->getQueryBuilder();
  960. $qb->select('*')
  961. ->from('share', 's')
  962. ->andWhere($qb->expr()->orX(
  963. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  964. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  965. ))
  966. ->andWhere(
  967. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL))
  968. );
  969. /**
  970. * Reshares for this user are shares where they are the owner.
  971. */
  972. if ($reshares === false) {
  973. $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
  974. } else {
  975. $qb->andWhere(
  976. $qb->expr()->orX(
  977. $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
  978. $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
  979. )
  980. );
  981. }
  982. $qb->innerJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
  983. $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
  984. $qb->orderBy('id');
  985. $cursor = $qb->executeQuery();
  986. $shares = [];
  987. while ($data = $cursor->fetch()) {
  988. $shares[$data['fileid']][] = $this->createShareObject($data);
  989. }
  990. $cursor->closeCursor();
  991. return $shares;
  992. }
  993. /**
  994. * @inheritdoc
  995. */
  996. public function getAccessList($nodes, $currentAccess): array {
  997. $ids = [];
  998. foreach ($nodes as $node) {
  999. $ids[] = $node->getId();
  1000. }
  1001. $qb = $this->dbConnection->getQueryBuilder();
  1002. $qb->select('share_with', 'file_source', 'token')
  1003. ->from('share')
  1004. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)))
  1005. ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
  1006. ->andWhere($qb->expr()->orX(
  1007. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  1008. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  1009. ));
  1010. $cursor = $qb->executeQuery();
  1011. $public = false;
  1012. $mail = [];
  1013. while ($row = $cursor->fetch()) {
  1014. $public = true;
  1015. if ($currentAccess === false) {
  1016. $mail[] = $row['share_with'];
  1017. } else {
  1018. $mail[$row['share_with']] = [
  1019. 'node_id' => $row['file_source'],
  1020. 'token' => $row['token']
  1021. ];
  1022. }
  1023. }
  1024. $cursor->closeCursor();
  1025. return ['public' => $public, 'mail' => $mail];
  1026. }
  1027. public function getAllShares(): iterable {
  1028. $qb = $this->dbConnection->getQueryBuilder();
  1029. $qb->select('*')
  1030. ->from('share')
  1031. ->where(
  1032. $qb->expr()->orX(
  1033. $qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL))
  1034. )
  1035. );
  1036. $cursor = $qb->executeQuery();
  1037. while ($data = $cursor->fetch()) {
  1038. try {
  1039. $share = $this->createShareObject($data);
  1040. } catch (InvalidShare $e) {
  1041. continue;
  1042. } catch (ShareNotFound $e) {
  1043. continue;
  1044. }
  1045. yield $share;
  1046. }
  1047. $cursor->closeCursor();
  1048. }
  1049. /**
  1050. * Extract the emails from the share
  1051. * It can be a single email, from the share_with field
  1052. * or a list of emails from the emails attributes field.
  1053. * @param IShare $share
  1054. * @return string[]
  1055. */
  1056. protected function getSharedWithEmails(IShare $share): array {
  1057. $attributes = $share->getAttributes();
  1058. if ($attributes === null) {
  1059. return [$share->getSharedWith()];
  1060. }
  1061. $emails = $attributes->getAttribute('shareWith', 'emails');
  1062. if (isset($emails) && is_array($emails) && !empty($emails)) {
  1063. return $emails;
  1064. }
  1065. return [$share->getSharedWith()];
  1066. }
  1067. }