ShareByMailProvider.php 40 KB

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