ShareByMailProvider.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  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. if ($shallow) {
  925. $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
  926. } else {
  927. $qb->andWhere($qb->expr()->like('f.path', $qb->createNamedParameter($this->dbConnection->escapeLikeParameter($node->getInternalPath()) . '/%')));
  928. }
  929. $qb->orderBy('id');
  930. $cursor = $qb->executeQuery();
  931. $shares = [];
  932. while ($data = $cursor->fetch()) {
  933. $shares[$data['fileid']][] = $this->createShareObject($data);
  934. }
  935. $cursor->closeCursor();
  936. return $shares;
  937. }
  938. /**
  939. * @inheritdoc
  940. */
  941. public function getAccessList($nodes, $currentAccess): array {
  942. $ids = [];
  943. foreach ($nodes as $node) {
  944. $ids[] = $node->getId();
  945. }
  946. $qb = $this->dbConnection->getQueryBuilder();
  947. $qb->select('share_with')
  948. ->from('share')
  949. ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(IShare::TYPE_EMAIL)))
  950. ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
  951. ->andWhere($qb->expr()->orX(
  952. $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
  953. $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
  954. ))
  955. ->setMaxResults(1);
  956. $cursor = $qb->executeQuery();
  957. $mail = $cursor->fetch() !== false;
  958. $cursor->closeCursor();
  959. return ['public' => $mail];
  960. }
  961. public function getAllShares(): iterable {
  962. $qb = $this->dbConnection->getQueryBuilder();
  963. $qb->select('*')
  964. ->from('share')
  965. ->where(
  966. $qb->expr()->orX(
  967. $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_EMAIL))
  968. )
  969. );
  970. $cursor = $qb->executeQuery();
  971. while ($data = $cursor->fetch()) {
  972. try {
  973. $share = $this->createShareObject($data);
  974. } catch (InvalidShare $e) {
  975. continue;
  976. } catch (ShareNotFound $e) {
  977. continue;
  978. }
  979. yield $share;
  980. }
  981. $cursor->closeCursor();
  982. }
  983. }