ShareByMailProvider.php 37 KB

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