ShareByMailProvider.php 39 KB

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