Completed
Pull Request — master (#347)
by Maxence
01:46
created

sendMailAboutExistingShares()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 9.1768
c 0
b 0
f 0
cc 5
nc 4
nop 2
1
<?php
2
/**
3
 * Circles - Bring cloud-users closer together.
4
 *
5
 * This file is licensed under the Affero General Public License version 3 or
6
 * later. See the COPYING file.
7
 *
8
 * @author Maxence Lange <[email protected]>
9
 * @copyright 2017
10
 * @license GNU AGPL version 3 or any later version
11
 *
12
 * This program is free software: you can redistribute it and/or modify
13
 * it under the terms of the GNU Affero General Public License as
14
 * published by the Free Software Foundation, either version 3 of the
15
 * License, or (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU Affero General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU Affero General Public License
23
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
24
 *
25
 */
26
27
28
namespace OCA\Circles\Circles;
29
30
use Exception;
31
use OC;
32
use OC\Share20\Share;
33
use OCA\Circles\AppInfo\Application;
34
use OCA\Circles\Db\SharesRequest;
35
use OCA\Circles\Db\TokensRequest;
36
use OCA\Circles\IBroadcaster;
37
use OCA\Circles\Model\Circle;
38
use OCA\Circles\Model\Member;
39
use OCA\Circles\Model\SharesToken;
40
use OCA\Circles\Model\SharingFrame;
41
use OCA\Circles\Service\ConfigService;
42
use OCA\Circles\Service\MiscService;
43
use OCP\AppFramework\QueryException;
44
use OCP\Defaults;
45
use OCP\Files\IRootFolder;
46
use OCP\Files\NotFoundException;
47
use OCP\IL10N;
48
use OCP\ILogger;
49
use OCP\IURLGenerator;
50
use OCP\IUser;
51
use OCP\IUserManager;
52
use OCP\Mail\IEMailTemplate;
53
use OCP\Mail\IMailer;
54
use OCP\Share\Exceptions\IllegalIDChangeException;
55
use OCP\Share\IShare;
56
use OCP\Util;
57
58
59
class FileSharingBroadcaster implements IBroadcaster {
60
61
62
	/** @var bool */
63
	private $initiated = false;
64
65
	/** @var IL10N */
66
	private $l10n = null;
67
68
	/** @var IMailer */
69
	private $mailer;
70
71
	/** @var IRootFolder */
72
	private $rootFolder;
73
74
	/** @var IUserManager */
75
	private $userManager;
76
77
	/** @var ILogger */
78
	private $logger;
79
80
	/** @var Defaults */
81
	private $defaults;
82
83
	/** @var IURLGenerator */
84
	private $urlGenerator;
85
86
	/** @var SharesRequest */
87
	private $sharesRequest;
88
89
	/** @var TokensRequest */
90
	private $tokensRequest;
91
92
	/** @var ConfigService */
93
	private $configService;
94
95
	/** @var MiscService */
96
	private $miscService;
97
98
99
	/**
100
	 * {@inheritdoc}
101
	 */
102
	public function init() {
103
		if ($this->initiated) {
104
			return;
105
		}
106
107
		$this->initiated = true;
108
		$this->l10n = OC::$server->getL10N(Application::APP_NAME);
109
		$this->mailer = OC::$server->getMailer();
110
		$this->rootFolder = OC::$server->getLazyRootFolder();
111
		$this->userManager = OC::$server->getUserManager();
112
		$this->logger = OC::$server->getLogger();
113
		$this->urlGenerator = OC::$server->getURLGenerator();
114
		try {
115
			$this->defaults = OC::$server->query(Defaults::class);
116
			$this->sharesRequest = OC::$server->query(SharesRequest::class);
117
			$this->tokensRequest = OC::$server->query(TokensRequest::class);
118
			$this->configService = OC::$server->query(ConfigService::class);
119
			$this->miscService = OC::$server->query(MiscService::class);
120
		} catch (QueryException $e) {
0 ignored issues
show
Bug introduced by
The class OCP\AppFramework\QueryException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
121
			\OC::$server->getLogger()
122
						->log(1, 'Circles: cannot init FileSharingBroadcaster - ' . $e->getMessage());
123
		}
124
	}
125
126
127
	/**
128
	 * {@inheritdoc}
129
	 */
130
	public function end() {
131
	}
132
133
134
	/**
135
	 * {@inheritdoc}
136
	 */
137
	public function createShareToCircle(SharingFrame $frame, Circle $circle) {
138
		if ($frame->is0Circle()) {
0 ignored issues
show
Unused Code introduced by
This if statement, and the following return statement can be replaced with return !$frame->is0Circle();.
Loading history...
139
			return false;
140
		}
141
142
		return true;
143
	}
144
145
146
	/**
147
	 * {@inheritdoc}
148
	 */
149
	public function deleteShareToCircle(SharingFrame $frame, Circle $circle) {
150
		return true;
151
	}
152
153
154
	/**
155
	 * {@inheritdoc}
156
	 */
157
	public function editShareToCircle(SharingFrame $frame, Circle $circle) {
158
		return true;
159
	}
160
161
162
	/**
163
	 * {@inheritdoc}
164
	 * @throws IllegalIDChangeException
165
	 */
166
	public function createShareToMember(SharingFrame $frame, Member $member) {
167
		if (!$frame->is0Circle()) {
168
			return false;
169
		}
170
171
		$payload = $frame->getPayload();
172
		if (!key_exists('share', $payload)) {
173
			return false;
174
		}
175
176
		$share = $this->generateShare($payload['share']);
177
		if ($member->getType() === Member::TYPE_MAIL || $member->getType() === Member::TYPE_CONTACT) {
178
			try {
179
				$circle = $frame->getCircle();
180
				$password = '';
181
182
				if ($this->configService->enforcePasswordProtection()) {
183
					$password = $this->miscService->token(15);
184
				}
185
186
				$token = $this->tokensRequest->generateTokenForMember($member, $share->getId(), $password);
187
				if ($token !== '') {
188
					$mails = [$member->getUserId()];
189
					if ($member->getType() === Member::TYPE_CONTACT) {
190
						$mails = $this->getMailsFromContact($member->getUserId());
191
					}
192
193
					foreach ($mails as $mail) {
194
						$this->sharedByMail($circle, $share, $mail, $token, $password);
195
					}
196
				}
197
			} catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
198
			}
199
		}
200
201
		return true;
202
	}
203
204
205
	/**
206
	 * {@inheritdoc}
207
	 */
208
	public function deleteShareToMember(SharingFrame $frame, Member $member) {
209
		return true;
210
	}
211
212
213
	/**
214
	 * {@inheritdoc}
215
	 */
216
	public function editShareToMember(SharingFrame $frame, Member $member) {
217
		return true;
218
	}
219
220
221
	/**
222
	 * @param Circle $circle
223
	 * @param Member $member
224
	 */
225
	public function sendMailAboutExistingShares(Circle $circle, Member $member) {
226
		$this->init();
227
		if ($member->getType() !== Member::TYPE_MAIL && $member->getType() !== Member::TYPE_CONTACT) {
228
			return;
229
		}
230
231
		$allShares = $this->sharesRequest->getSharesForCircle($member->getCircleId());
232
		$knownShares = array_map(
233
			function(SharesToken $shareToken) {
234
				return $shareToken->getShareId();
235
			},
236
			$this->tokensRequest->getTokensFromMember($member)
237
		);
238
239
		$unknownShares = [];
240
		foreach ($allShares as $share) {
241
			if (!in_array($share['id'], $knownShares)) {
242
				$unknownShares[] = $share;
243
			}
244
		}
245
246
		$author = $circle->getViewer()
247
						 ->getUserId();
248
		$this->sendMailExitingShares(
249
			$unknownShares, MiscService::getDisplay($author, Member::TYPE_USER), $member, $circle->getName()
250
		);
251
	}
252
253
254
	/**
255
	 * recreate the share from the JSON payload.
256
	 *
257
	 * @param array $data
258
	 *
259
	 * @return IShare
0 ignored issues
show
Documentation introduced by
Should the return type not be Share?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
260
	 * @throws IllegalIDChangeException
261
	 */
262
	private function generateShare($data) {
263
		$this->logger->log(0, 'Regenerate shares from payload: ' . json_encode($data));
264
265
		$share = new Share($this->rootFolder, $this->userManager);
266
		$share->setId($data['id']);
267
		$share->setSharedBy($data['sharedBy']);
268
		$share->setSharedWith($data['sharedWith']);
269
		$share->setNodeId($data['nodeId']);
270
		$share->setShareOwner($data['shareOwner']);
271
		$share->setPermissions($data['permissions']);
272
		$share->setToken($data['token']);
273
		$share->setPassword($data['password']);
274
275
		return $share;
276
	}
277
278
279
	/**
280
	 * @param Circle $circle
281
	 * @param IShare $share
282
	 * @param string $email
283
	 * @param string $token
284
	 * @param string $password
285
	 */
286
	private function sharedByMail(Circle $circle, IShare $share, $email, $token, $password) {
287
		// genelink
288
		$link = $this->urlGenerator->linkToRouteAbsolute(
289
			'files_sharing.sharecontroller.showShare',
290
			['token' => $token]
291
		);
292
293
		try {
294
			$this->sendMail(
295
				$share->getNode()
296
					  ->getName(), $link,
297
				MiscService::getDisplay($share->getSharedBy(), Member::TYPE_USER),
298
				$circle->getName(), $email
299
			);
300
			$this->sendPasswordByMail(
301
				$share, MiscService::getDisplay($share->getSharedBy(), Member::TYPE_USER),
302
				$email, $password
303
			);
304
		} catch (Exception $e) {
305
			OC::$server->getLogger()
306
					   ->log(1, 'Circles::sharedByMail - mail were not sent: ' . $e->getMessage());
307
		}
308
	}
309
310
311
	/**
312
	 * @param $fileName
313
	 * @param string $link
314
	 * @param string $author
315
	 * @param $circleName
316
	 * @param string $email
317
	 *
318
	 * @throws Exception
319
	 */
320
	protected function sendMail($fileName, $link, $author, $circleName, $email) {
321
		$message = $this->mailer->createMessage();
322
323
		$this->logger->log(
324
			0, "Sending mail to circle '" . $circleName . "': " . $email . ' file: ' . $fileName
325
			   . ' - link: ' . $link
326
		);
327
328
		$subject = $this->l10n->t('%s shared »%s« with you.', [$author, $fileName]);
329
		$text = $this->l10n->t('%s shared »%s« with \'%s\'.', [$author, $fileName, $circleName]);
330
331
		$emailTemplate =
332
			$this->generateEmailTemplate($subject, $text, $fileName, $link, $author, $circleName);
333
334
		$instanceName = $this->defaults->getName();
335
		$senderName = $this->l10n->t('%s on %s', [$author, $instanceName]);
336
337
		$message->setFrom([Util::getDefaultEmailAddress($instanceName) => $senderName]);
338
		$message->setSubject($subject);
339
		$message->setPlainBody($emailTemplate->renderText());
340
		$message->setHtmlBody($emailTemplate->renderHtml());
341
		$message->setTo([$email]);
342
343
		$this->mailer->send($message);
344
	}
345
346
347
	/**
348
	 * @param IShare $share
349
	 * @param string $circleName
350
	 * @param string $email
351
	 *
352
	 * @param $password
353
	 *
354
	 * @throws NotFoundException
355
	 * @throws Exception
356
	 */
357
	protected function sendPasswordByMail(IShare $share, $circleName, $email, $password) {
358
		if (!$this->configService->sendPasswordByMail() || $password === '') {
359
			return;
360
		}
361
362
		$message = $this->mailer->createMessage();
363
364
		$this->logger->log(0, "Sending password mail to circle '" . $circleName . "': " . $email);
365
366
		$filename = $share->getNode()
367
						  ->getName();
368
		$initiator = $share->getSharedBy();
369
		$shareWith = $share->getSharedWith();
370
371
		$initiatorUser = $this->userManager->get($initiator);
372
		$initiatorDisplayName =
373
			($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
0 ignored issues
show
Bug introduced by
The class OCP\IUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
374
		$initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
0 ignored issues
show
Bug introduced by
The class OCP\IUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
375
376
		$plainBodyPart = $this->l10n->t(
377
			"%1\$s shared »%2\$s« with you.\nYou should have already received a separate mail with a link to access it.\n",
378
			[$initiatorDisplayName, $filename]
379
		);
380
		$htmlBodyPart = $this->l10n->t(
381
			'%1$s shared »%2$s« with you. You should have already received a separate mail with a link to access it.',
382
			[$initiatorDisplayName, $filename]
383
		);
384
385
		$emailTemplate = $this->mailer->createEMailTemplate(
386
			'sharebymail.RecipientPasswordNotification', [
387
														   'filename'       => $filename,
388
														   'password'       => $password,
389
														   'initiator'      => $initiatorDisplayName,
390
														   'initiatorEmail' => $initiatorEmailAddress,
391
														   'shareWith'      => $shareWith,
392
													   ]
393
		);
394
395
		$emailTemplate->setSubject(
396
			$this->l10n->t(
397
				'Password to access »%1$s« shared to you by %2$s', [$filename, $initiatorDisplayName]
398
			)
399
		);
400
		$emailTemplate->addHeader();
401
		$emailTemplate->addHeading($this->l10n->t('Password to access »%s«', [$filename]), false);
402
		$emailTemplate->addBodyText(htmlspecialchars($htmlBodyPart), $plainBodyPart);
403
		$emailTemplate->addBodyText($this->l10n->t('It is protected with the following password:'));
404
		$emailTemplate->addBodyText($password);
405
406
		// The "From" contains the sharers name
407
		$instanceName = $this->defaults->getName();
408
		$senderName = $this->l10n->t(
409
			'%1$s via %2$s',
410
			[
411
				$initiatorDisplayName,
412
				$instanceName
413
			]
414
		);
415
		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
416 View Code Duplication
		if ($initiatorEmailAddress !== null) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
417
			$message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
418
			$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
419
		} else {
420
			$emailTemplate->addFooter();
421
		}
422
423
		$message->setTo([$email]);
424
		$message->useTemplate($emailTemplate);
425
		$this->mailer->send($message);
426
	}
427
428
429
	/**
430
	 * @param $subject
431
	 * @param $text
432
	 * @param $fileName
433
	 * @param $link
434
	 * @param string $author
435
	 * @param string $circleName
436
	 *
437
	 * @return IEMailTemplate
438
	 */
439
	private function generateEmailTemplate($subject, $text, $fileName, $link, $author, $circleName
440
	) {
441
		$emailTemplate = $this->mailer->createEMailTemplate(
442
			'circles.ShareNotification', [
443
										   'fileName'   => $fileName,
444
										   'fileLink'   => $link,
445
										   'author'     => $author,
446
										   'circleName' => $circleName,
447
									   ]
448
		);
449
450
		$emailTemplate->addHeader();
451
		$emailTemplate->addHeading($subject, false);
452
		$emailTemplate->addBodyText(
453
			htmlspecialchars($text) . '<br>' . htmlspecialchars(
454
				$this->l10n->t('Click the button below to open it.')
455
			), $text
456
		);
457
		$emailTemplate->addBodyButton(
458
			$this->l10n->t('Open »%s«', [htmlspecialchars($fileName)]), $link
459
		);
460
461
		return $emailTemplate;
462
	}
463
464
465
	/**
466
	 * @param array $unknownShares
467
	 * @param string $author
468
	 * @param Member $member
469
	 * @param string $circleName
470
	 */
471
	private function sendMailExitingShares(array $unknownShares, $author, Member $member, $circleName) {
472
		$password = '';
473
		if ($this->configService->enforcePasswordProtection()) {
474
			try {
475
				$password = $this->miscService->token(15);
476
			} catch (Exception $e) {
477
				return;
478
			}
479
		}
480
481
		$data = [];
482
		foreach ($unknownShares as $share) {
483
			$data[] = $this->getMailLinkFromShare($share, $member, $password);
484
		}
485
486
487
		if (sizeof($data) === 0) {
488
			return;
489
		}
490
491
		try {
492
			$template = $this->generateMailExitingShares($author, $circleName);
493
			$this->fillMailExistingShares($template, $data);
494
			$this->sendMailExistingShares($template, $author, $member->getUserId());
495
			$this->sendPasswordExistingShares($author, $member->getUserId(), $password);
496
		} catch (Exception $e) {
497
			$this->logger->log(2, 'Failed to send mail about existing share ' . $e->getMessage());
498
		}
499
	}
500
501
502
	/**
503
	 * @param $author
504
	 * @param string $email
505
	 *
506
	 * @param $password
507
	 *
508
	 * @throws Exception
509
	 */
510
	protected function sendPasswordExistingShares($author, $email, $password) {
511
		if (!$this->configService->sendPasswordByMail() || $password === '') {
512
			return;
513
		}
514
515
		$message = $this->mailer->createMessage();
516
517
		$authorUser = $this->userManager->get($author);
518
		$authorName = ($authorUser instanceof IUser) ? $authorUser->getDisplayName() : $author;
0 ignored issues
show
Bug introduced by
The class OCP\IUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
519
		$authorEmail = ($authorUser instanceof IUser) ? $authorUser->getEMailAddress() : null;
0 ignored issues
show
Bug introduced by
The class OCP\IUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
520
521
		$this->logger->log(0, "Sending password mail about existing files to '" . $email . "'");
522
523
		$plainBodyPart = $this->l10n->t(
524
			"%1\$s shared multiple files with you.\nYou should have already received a separate mail with a link to access them.\n",
525
			[$authorName]
526
		);
527
		$htmlBodyPart = $this->l10n->t(
528
			'%1$s shared multiple files with you. You should have already received a separate mail with a link to access them.',
529
			[$authorName]
530
		);
531
532
		$emailTemplate = $this->mailer->createEMailTemplate(
533
			'sharebymail.RecipientPasswordNotification', [
534
														   'password' => $password,
535
														   'author'   => $author
536
													   ]
537
		);
538
539
		$emailTemplate->setSubject(
540
			$this->l10n->t(
541
				'Password to access files shared to you by %1$s', [$authorName]
542
			)
543
		);
544
		$emailTemplate->addHeader();
545
		$emailTemplate->addHeading($this->l10n->t('Password to access files'), false);
546
		$emailTemplate->addBodyText(htmlspecialchars($htmlBodyPart), $plainBodyPart);
547
		$emailTemplate->addBodyText($this->l10n->t('It is protected with the following password:'));
548
		$emailTemplate->addBodyText($password);
549
550
		// The "From" contains the sharers name
551
		$instanceName = $this->defaults->getName();
552
		$senderName = $this->l10n->t(
553
			'%1$s via %2$s',
554
			[
555
				$authorName,
556
				$instanceName
557
			]
558
		);
559
560
		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
561 View Code Duplication
		if ($authorEmail !== null) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
562
			$message->setReplyTo([$authorEmail => $authorName]);
563
			$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
564
		} else {
565
			$emailTemplate->addFooter();
566
		}
567
568
		$message->setTo([$email]);
569
		$message->useTemplate($emailTemplate);
570
		$this->mailer->send($message);
571
	}
572
573
	/**
574
	 * @param array $share
575
	 * @param Member $member
576
	 * @param string $password
577
	 *
578
	 * @return array
579
	 */
580
	private function getMailLinkFromShare(array $share, Member $member, $password) {
581
		$token = $this->tokensRequest->generateTokenForMember($member, $share['id'], $password);
582
		$link = $this->urlGenerator->linkToRouteAbsolute(
583
			'files_sharing.sharecontroller.showShare',
584
			['token' => $token]
585
		);
586
		$author = $share['uid_initiator'];
587
588
		$filename = basename($share['file_target']);
589
590
		return [
591
			'author'   => $author,
592
			'link'     => $link,
593
			'password' => $password,
594
			'filename' => $filename
595
		];
596
	}
597
598
599
	/**
600
	 * @param $author
601
	 * @param string $circleName
602
	 *
603
	 * @return IEMailTemplate
604
	 * @throws Exception
605
	 */
606
	protected function generateMailExitingShares($author, $circleName) {
607
		$this->logger->log(
608
			0, "Generating mail about existing share mail from '" . $author . "' in "
609
			   . $circleName
610
		);
611
612
		$emailTemplate = $this->mailer->createEMailTemplate('circles.ExistingShareNotification', []);
613
		$emailTemplate->addHeader();
614
615
		$text = $this->l10n->t('%s shared multiple files with \'%s\'.', [$author, $circleName]);
616
		$emailTemplate->addBodyText(htmlspecialchars($text), $text);
617
618
		return $emailTemplate;
619
	}
620
621
622
	/**
623
	 * @param IEMailTemplate $emailTemplate
624
	 * @param array $data
625
	 */
626
	protected function fillMailExistingShares(IEMailTemplate $emailTemplate, array $data) {
627
		foreach ($data as $item) {
628
//			$text = $this->l10n->t('%s shared »%s« with you.', [$item['author'], $item['filename']]);
629
//			$emailTemplate->addBodyText(
630
//				htmlspecialchars($text) . '<br>' . htmlspecialchars(
631
//					$this->l10n->t('Click the button below to open it.')
632
//				), $text
633
//			);
634
			$emailTemplate->addBodyButton(
635
				$this->l10n->t('Open »%s«', [htmlspecialchars($item['filename'])]), $item['link']
636
			);
637
		}
638
	}
639
640
641
	/**
642
	 * @param IEMailTemplate $emailTemplate
643
	 * @param $author
644
	 * @param $recipient
645
	 *
646
	 * @throws Exception
647
	 */
648
	protected function sendMailExistingShares(IEMailTemplate $emailTemplate, $author, $recipient) {
649
		$subject = $this->l10n->t('%s shared multiple files with you.', [$author]);
650
//		$emailTemplate->addHeading($subject, false);
651
652
		$instanceName = $this->defaults->getName();
653
		$senderName = $this->l10n->t('%s on %s', [$author, $instanceName]);
654
655
		$message = $this->mailer->createMessage();
656
657
		$message->setFrom([Util::getDefaultEmailAddress($instanceName) => $senderName]);
658
		$message->setSubject($subject);
659
		$message->setPlainBody($emailTemplate->renderText());
660
		$message->setHtmlBody($emailTemplate->renderHtml());
661
		$message->setTo([$recipient]);
662
663
		$this->mailer->send($message);
664
665
666
//		$message = $this->mailer->createMessage();
667
//
668
		//
669
		//
670
		//
671
672
673
//		$filename = $share->getNode()
674
//						  ->getName();
675
//		$initiator = $share->getSharedBy();
676
//		$shareWith = $share->getSharedWith();
677
//
678
//		$initiatorUser = $this->userManager->get($initiator);
679
//		$initiatorDisplayName =
680
//			($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
681
//		$initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
682
683
//		$plainBodyPart = $this->l10n->t(
684
//			"%1\$s shared »%2\$s« with you.\nYou should have already received a separate mail with a link to access it.\n",
685
//			[$initiatorDisplayName, $filename]
686
//		);
687
//		$htmlBodyPart = $this->l10n->t(
688
//			'%1$s shared »%2$s« with you. You should have already received a separate mail with a link to access it.',
689
//			[$initiatorDisplayName, $filename]
690
//		);
691
//
692
//		$emailTemplate = $this->mailer->createEMailTemplate(
693
//			'sharebymail.RecipientPasswordNotification', [
694
//														   'filename'       => $filename,
695
//														   'password'       => $password,
696
//														   'initiator'      => $initiatorDisplayName,
697
//														   'initiatorEmail' => $initiatorEmailAddress,
698
//														   'shareWith'      => $shareWith,
699
//													   ]
700
//		);
701
//
702
//		$emailTemplate->setSubject(
703
//			$this->l10n->t(
704
//				'Password to access »%1$s« shared to you by %2$s', [$filename, $initiatorDisplayName]
705
//			)
706
//		);
707
//		$emailTemplate->addHeader();
708
//		$emailTemplate->addHeading($this->l10n->t('Password to access »%s«', [$filename]), false);
709
//		$emailTemplate->addBodyText(htmlspecialchars($htmlBodyPart), $plainBodyPart);
710
//		$emailTemplate->addBodyText($this->l10n->t('It is protected with the following password:'));
711
//		$emailTemplate->addBodyText($password);
712
713
		// The "From" contains the sharers name
714
//		$instanceName = $this->defaults->getName();
715
//		$senderName = $this->l10n->t(
716
//			'%1$s via %2$s',
717
//			[
718
//				$initiatorDisplayName,
719
//				$instanceName
720
//			]
721
//		);
722
//		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
723
//		if ($initiatorEmailAddress !== null) {
724
//			$message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
725
//			$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
726
//		} else {
727
//			$emailTemplate->addFooter();
728
//		}
729
//
730
//		$message->setTo([$email]);
731
//		$message->useTemplate($emailTemplate);
732
//		$this->mailer->send($message);
733
	}
734
735
736
	/**
737
	 * @param string $contactId
738
	 *
739
	 * @return array
740
	 */
741
	private function getMailsFromContact(string $contactId): array {
742
		$contact = MiscService::getContactData($contactId);
743
		if (!key_exists('EMAIL', $contact)) {
744
			return [];
745
		}
746
747
		return $contact['EMAIL'];
748
	}
749
750
}
751