Completed
Pull Request — master (#332)
by Maxence
01:54
created

FileSharingBroadcaster   B

Complexity

Total Complexity 51

Size/Duplication

Total Lines 668
Duplicated Lines 1.8 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
wmc 51
lcom 1
cbo 8
dl 12
loc 668
rs 7.852
c 0
b 0
f 0

20 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 23 3
A end() 0 2 1
A createShareToCircle() 0 7 2
A deleteShareToCircle() 0 3 1
A editShareToCircle() 0 3 1
B createShareToMember() 0 30 9
A deleteShareToMember() 0 3 1
A editShareToMember() 0 3 1
A sendMailAboutExistingShares() 0 27 5
A generateShare() 0 15 1
A sharedByMail() 0 23 2
A sendMail() 0 25 1
B sendPasswordByMail() 6 70 6
A generateEmailTemplate() 0 24 1
A sendMailExitingShares() 0 26 5
B sendPasswordExistingShares() 6 62 6
A getMailLinkFromShare() 0 17 1
A generateMailExitingShares() 0 14 1
A fillMailExistingShares() 0 13 2
B sendMailExistingShares() 0 86 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like FileSharingBroadcaster often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use FileSharingBroadcaster, and based on these observations, apply Extract Interface, too.

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\Exceptions\TokenDoesNotExistException;
37
use OCA\Circles\IBroadcaster;
38
use OCA\Circles\Model\Circle;
39
use OCA\Circles\Model\Member;
40
use OCA\Circles\Model\SharesToken;
41
use OCA\Circles\Model\SharingFrame;
42
use OCA\Circles\Service\ConfigService;
43
use OCA\Circles\Service\MiscService;
44
use OCP\AppFramework\QueryException;
45
use OCP\Defaults;
46
use OCP\Files\IRootFolder;
47
use OCP\Files\NotFoundException;
48
use OCP\IL10N;
49
use OCP\ILogger;
50
use OCP\IURLGenerator;
51
use OCP\IUser;
52
use OCP\IUserManager;
53
use OCP\Mail\IEMailTemplate;
54
use OCP\Mail\IMailer;
55
use OCP\Share\Exceptions\IllegalIDChangeException;
56
use OCP\Share\IShare;
57
use OCP\Util;
58
59
60
class FileSharingBroadcaster implements IBroadcaster {
61
62
63
	/** @var bool */
64
	private $initiated = false;
65
66
	/** @var IL10N */
67
	private $l10n = null;
68
69
	/** @var IMailer */
70
	private $mailer;
71
72
	/** @var IRootFolder */
73
	private $rootFolder;
74
75
	/** @var IUserManager */
76
	private $userManager;
77
78
	/** @var ILogger */
79
	private $logger;
80
81
	/** @var Defaults */
82
	private $defaults;
83
84
	/** @var IURLGenerator */
85
	private $urlGenerator;
86
87
	/** @var SharesRequest */
88
	private $sharesRequest;
89
90
	/** @var TokensRequest */
91
	private $tokensRequest;
92
93
	/** @var ConfigService */
94
	private $configService;
95
96
	/** @var MiscService */
97
	private $miscService;
98
99
100
	/**
101
	 * {@inheritdoc}
102
	 */
103
	public function init() {
104
		if ($this->initiated) {
105
			return;
106
		}
107
108
		$this->initiated = true;
109
		$this->l10n = OC::$server->getL10N(Application::APP_NAME);
110
		$this->mailer = OC::$server->getMailer();
111
		$this->rootFolder = OC::$server->getLazyRootFolder();
112
		$this->userManager = OC::$server->getUserManager();
113
		$this->logger = OC::$server->getLogger();
114
		$this->urlGenerator = OC::$server->getURLGenerator();
115
		try {
116
			$this->defaults = OC::$server->query(Defaults::class);
117
			$this->sharesRequest = OC::$server->query(SharesRequest::class);
118
			$this->tokensRequest = OC::$server->query(TokensRequest::class);
119
			$this->configService = OC::$server->query(ConfigService::class);
120
			$this->miscService = OC::$server->query(MiscService::class);
121
		} 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...
122
			\OC::$server->getLogger()
123
						->log(1, 'Circles: cannot init FileSharingBroadcaster - ' . $e->getMessage());
124
		}
125
	}
126
127
128
	/**
129
	 * {@inheritdoc}
130
	 */
131
	public function end() {
132
	}
133
134
135
	/**
136
	 * {@inheritdoc}
137
	 */
138
	public function createShareToCircle(SharingFrame $frame, Circle $circle) {
139
		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...
140
			return false;
141
		}
142
143
		return true;
144
	}
145
146
147
	/**
148
	 * {@inheritdoc}
149
	 */
150
	public function deleteShareToCircle(SharingFrame $frame, Circle $circle) {
151
		return true;
152
	}
153
154
155
	/**
156
	 * {@inheritdoc}
157
	 */
158
	public function editShareToCircle(SharingFrame $frame, Circle $circle) {
159
		return true;
160
	}
161
162
163
	/**
164
	 * {@inheritdoc}
165
	 * @throws IllegalIDChangeException
166
	 */
167
	public function createShareToMember(SharingFrame $frame, Member $member) {
168
		if (!$frame->is0Circle()) {
169
			return false;
170
		}
171
172
		$payload = $frame->getPayload();
173
		if (!key_exists('share', $payload)) {
174
			return false;
175
		}
176
177
		$share = $this->generateShare($payload['share']);
178
		if ($member->getType() === Member::TYPE_MAIL || $member->getType() === Member::TYPE_CONTACT) {
179
			try {
180
				$circle = $frame->getCircle();
181
				$password = '';
182
183
				if ($this->configService->enforcePasswordProtection()) {
184
					$password = $this->miscService->uuid(15);
185
				}
186
				$token = $this->tokensRequest->generateTokenForMember($member, $share->getId(), $password);
187
				if ($token !== '') {
188
					$this->sharedByMail($circle, $share, $member->getUserId(), $token, $password);
189
				}
190
			} catch (TokenDoesNotExistException $e) {
191
			} catch (NotFoundException $e) {
0 ignored issues
show
Bug introduced by
The class OCP\Files\NotFoundException 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...
192
			}
193
		}
194
195
		return true;
196
	}
197
198
199
	/**
200
	 * {@inheritdoc}
201
	 */
202
	public function deleteShareToMember(SharingFrame $frame, Member $member) {
203
		return true;
204
	}
205
206
207
	/**
208
	 * {@inheritdoc}
209
	 */
210
	public function editShareToMember(SharingFrame $frame, Member $member) {
211
		return true;
212
	}
213
214
215
	/**
216
	 * @param Circle $circle
217
	 * @param Member $member
218
	 */
219
	public function sendMailAboutExistingShares(Circle $circle, Member $member) {
220
		$this->init();
221
		if ($member->getType() !== Member::TYPE_MAIL && $member->getType() !== Member::TYPE_CONTACT) {
222
			return;
223
		}
224
225
		$allShares = $this->sharesRequest->getSharesForCircle($member->getCircleId());
226
		$knownShares = array_map(
227
			function(SharesToken $shareToken) {
228
				return $shareToken->getShareId();
229
			},
230
			$this->tokensRequest->getTokensFromMember($member)
231
		);
232
233
		$unknownShares = [];
234
		foreach ($allShares as $share) {
235
			if (!in_array($share['id'], $knownShares)) {
236
				$unknownShares[] = $share;
237
			}
238
		}
239
240
		$author = $circle->getViewer()
241
						 ->getUserId();
242
		$this->sendMailExitingShares(
243
			$unknownShares, MiscService::getDisplay($author, Member::TYPE_USER), $member, $circle->getName()
244
		);
245
	}
246
247
248
	/**
249
	 * recreate the share from the JSON payload.
250
	 *
251
	 * @param array $data
252
	 *
253
	 * @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...
254
	 * @throws IllegalIDChangeException
255
	 */
256
	private function generateShare($data) {
257
		$this->logger->log(0, 'Regenerate shares from payload: ' . json_encode($data));
258
259
		$share = new Share($this->rootFolder, $this->userManager);
260
		$share->setId($data['id']);
261
		$share->setSharedBy($data['sharedBy']);
262
		$share->setSharedWith($data['sharedWith']);
263
		$share->setNodeId($data['nodeId']);
264
		$share->setShareOwner($data['shareOwner']);
265
		$share->setPermissions($data['permissions']);
266
		$share->setToken($data['token']);
267
		$share->setPassword($data['password']);
268
269
		return $share;
270
	}
271
272
273
	/**
274
	 * @param Circle $circle
275
	 * @param IShare $share
276
	 * @param string $email
277
	 * @param string $token
278
	 * @param string $password
279
	 */
280
	private function sharedByMail(Circle $circle, IShare $share, $email, $token, $password) {
281
		// genelink
282
		$link = $this->urlGenerator->linkToRouteAbsolute(
283
			'files_sharing.sharecontroller.showShare',
284
			['token' => $token]
285
		);
286
287
		try {
288
			$this->sendMail(
289
				$share->getNode()
290
					  ->getName(), $link,
291
				MiscService::getDisplay($share->getSharedBy(), Member::TYPE_USER),
292
				$circle->getName(), $email
293
			);
294
			$this->sendPasswordByMail(
295
				$share, MiscService::getDisplay($share->getSharedBy(), Member::TYPE_USER),
296
				$email, $password
297
			);
298
		} catch (Exception $e) {
299
			OC::$server->getLogger()
300
					   ->log(1, 'Circles::sharedByMail - mail were not sent: ' . $e->getMessage());
301
		}
302
	}
303
304
305
	/**
306
	 * @param $fileName
307
	 * @param string $link
308
	 * @param string $author
309
	 * @param $circleName
310
	 * @param string $email
311
	 *
312
	 * @throws Exception
313
	 */
314
	protected function sendMail($fileName, $link, $author, $circleName, $email) {
315
		$message = $this->mailer->createMessage();
316
317
		$this->logger->log(
318
			0, "Sending mail to circle '" . $circleName . "': " . $email . ' file: ' . $fileName
319
			   . ' - link: ' . $link
320
		);
321
322
		$subject = $this->l10n->t('%s shared »%s« with you.', [$author, $fileName]);
323
		$text = $this->l10n->t('%s shared »%s« with \'%s\'.', [$author, $fileName, $circleName]);
324
325
		$emailTemplate =
326
			$this->generateEmailTemplate($subject, $text, $fileName, $link, $author, $circleName);
327
328
		$instanceName = $this->defaults->getName();
329
		$senderName = $this->l10n->t('%s on %s', [$author, $instanceName]);
330
331
		$message->setFrom([Util::getDefaultEmailAddress($instanceName) => $senderName]);
332
		$message->setSubject($subject);
333
		$message->setPlainBody($emailTemplate->renderText());
334
		$message->setHtmlBody($emailTemplate->renderHtml());
335
		$message->setTo([$email]);
336
337
		$this->mailer->send($message);
338
	}
339
340
341
	/**
342
	 * @param IShare $share
343
	 * @param string $circleName
344
	 * @param string $email
345
	 *
346
	 * @param $password
347
	 *
348
	 * @throws NotFoundException
349
	 * @throws Exception
350
	 */
351
	protected function sendPasswordByMail(IShare $share, $circleName, $email, $password) {
352
		if (!$this->configService->sendPasswordByMail() || $password === '') {
353
			return;
354
		}
355
356
		$message = $this->mailer->createMessage();
357
358
		$this->logger->log(0, "Sending password mail to circle '" . $circleName . "': " . $email);
359
360
		$filename = $share->getNode()
361
						  ->getName();
362
		$initiator = $share->getSharedBy();
363
		$shareWith = $share->getSharedWith();
364
365
		$initiatorUser = $this->userManager->get($initiator);
366
		$initiatorDisplayName =
367
			($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...
368
		$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...
369
370
		$plainBodyPart = $this->l10n->t(
371
			"%1\$s shared »%2\$s« with you.\nYou should have already received a separate mail with a link to access it.\n",
372
			[$initiatorDisplayName, $filename]
373
		);
374
		$htmlBodyPart = $this->l10n->t(
375
			'%1$s shared »%2$s« with you. You should have already received a separate mail with a link to access it.',
376
			[$initiatorDisplayName, $filename]
377
		);
378
379
		$emailTemplate = $this->mailer->createEMailTemplate(
380
			'sharebymail.RecipientPasswordNotification', [
381
														   'filename'       => $filename,
382
														   'password'       => $password,
383
														   'initiator'      => $initiatorDisplayName,
384
														   'initiatorEmail' => $initiatorEmailAddress,
385
														   'shareWith'      => $shareWith,
386
													   ]
387
		);
388
389
		$emailTemplate->setSubject(
390
			$this->l10n->t(
391
				'Password to access »%1$s« shared to you by %2$s', [$filename, $initiatorDisplayName]
392
			)
393
		);
394
		$emailTemplate->addHeader();
395
		$emailTemplate->addHeading($this->l10n->t('Password to access »%s«', [$filename]), false);
396
		$emailTemplate->addBodyText(htmlspecialchars($htmlBodyPart), $plainBodyPart);
397
		$emailTemplate->addBodyText($this->l10n->t('It is protected with the following password:'));
398
		$emailTemplate->addBodyText($password);
399
400
		// The "From" contains the sharers name
401
		$instanceName = $this->defaults->getName();
402
		$senderName = $this->l10n->t(
403
			'%1$s via %2$s',
404
			[
405
				$initiatorDisplayName,
406
				$instanceName
407
			]
408
		);
409
		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
410 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...
411
			$message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
412
			$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
413
		} else {
414
			$emailTemplate->addFooter();
415
		}
416
417
		$message->setTo([$email]);
418
		$message->useTemplate($emailTemplate);
419
		$this->mailer->send($message);
420
	}
421
422
423
	/**
424
	 * @param $subject
425
	 * @param $text
426
	 * @param $fileName
427
	 * @param $link
428
	 * @param string $author
429
	 * @param string $circleName
430
	 *
431
	 * @return IEMailTemplate
432
	 */
433
	private function generateEmailTemplate($subject, $text, $fileName, $link, $author, $circleName
434
	) {
435
		$emailTemplate = $this->mailer->createEMailTemplate(
436
			'circles.ShareNotification', [
437
										   'fileName'   => $fileName,
438
										   'fileLink'   => $link,
439
										   'author'     => $author,
440
										   'circleName' => $circleName,
441
									   ]
442
		);
443
444
		$emailTemplate->addHeader();
445
		$emailTemplate->addHeading($subject, false);
446
		$emailTemplate->addBodyText(
447
			htmlspecialchars($text) . '<br>' . htmlspecialchars(
448
				$this->l10n->t('Click the button below to open it.')
449
			), $text
450
		);
451
		$emailTemplate->addBodyButton(
452
			$this->l10n->t('Open »%s«', [htmlspecialchars($fileName)]), $link
453
		);
454
455
		return $emailTemplate;
456
	}
457
458
459
	/**
460
	 * @param array $unknownShares
461
	 * @param string $author
462
	 * @param Member $member
463
	 * @param string $circleName
464
	 */
465
	private function sendMailExitingShares(array $unknownShares, $author, Member $member, $circleName) {
466
		$password = '';
467
		if ($this->configService->enforcePasswordProtection()) {
468
			$password = $this->miscService->uuid(15);
469
		}
470
471
		$data = [];
472
		$this->miscService->log('#### ' . $password);
473
		foreach ($unknownShares as $share) {
474
			$data[] = $this->getMailLinkFromShare($share, $member, $password);
475
		}
476
477
478
		if (sizeof($data) === 0) {
479
			return;
480
		}
481
482
		try {
483
			$template = $this->generateMailExitingShares($author, $circleName);
484
			$this->fillMailExistingShares($template, $data);
485
			$this->sendMailExistingShares($template, $author, $member->getUserId());
486
			$this->sendPasswordExistingShares($author, $member->getUserId(), $password);
487
		} catch (Exception $e) {
488
			$this->logger->log(2, 'Failed to send mail about existing share ' . $e->getMessage());
489
		}
490
	}
491
492
493
	/**
494
	 * @param $author
495
	 * @param string $email
496
	 *
497
	 * @param $password
498
	 *
499
	 * @throws Exception
500
	 */
501
	protected function sendPasswordExistingShares($author, $email, $password) {
502
		if (!$this->configService->sendPasswordByMail() || $password === '') {
503
			return;
504
		}
505
506
		$message = $this->mailer->createMessage();
507
508
		$authorUser = $this->userManager->get($author);
509
		$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...
510
		$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...
511
512
		$this->logger->log(0, "Sending password mail about existing files to '" . $email . "'");
513
514
		$plainBodyPart = $this->l10n->t(
515
			"%1\$s shared multiple files with you.\nYou should have already received a separate mail with a link to access them.\n",
516
			[$authorName]
517
		);
518
		$htmlBodyPart = $this->l10n->t(
519
			'%1$s shared multiple files with you. You should have already received a separate mail with a link to access them.',
520
			[$authorName]
521
		);
522
523
		$emailTemplate = $this->mailer->createEMailTemplate(
524
			'sharebymail.RecipientPasswordNotification', [
525
														   'password' => $password,
526
														   'author'   => $author
527
													   ]
528
		);
529
530
		$emailTemplate->setSubject(
531
			$this->l10n->t(
532
				'Password to access files shared to you by %1$s', [$authorName]
533
			)
534
		);
535
		$emailTemplate->addHeader();
536
		$emailTemplate->addHeading($this->l10n->t('Password to access files'), false);
537
		$emailTemplate->addBodyText(htmlspecialchars($htmlBodyPart), $plainBodyPart);
538
		$emailTemplate->addBodyText($this->l10n->t('It is protected with the following password:'));
539
		$emailTemplate->addBodyText($password);
540
541
		// The "From" contains the sharers name
542
		$instanceName = $this->defaults->getName();
543
		$senderName = $this->l10n->t(
544
			'%1$s via %2$s',
545
			[
546
				$authorName,
547
				$instanceName
548
			]
549
		);
550
551
		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
552 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...
553
			$message->setReplyTo([$authorEmail => $authorName]);
554
			$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
555
		} else {
556
			$emailTemplate->addFooter();
557
		}
558
559
		$message->setTo([$email]);
560
		$message->useTemplate($emailTemplate);
561
		$this->mailer->send($message);
562
	}
563
564
	/**
565
	 * @param array $share
566
	 * @param Member $member
567
	 * @param string $password
568
	 *
569
	 * @return array
570
	 */
571
	private function getMailLinkFromShare(array $share, Member $member, $password) {
572
		$token = $this->tokensRequest->generateTokenForMember($member, $share['id'], $password);
573
		$link = $this->urlGenerator->linkToRouteAbsolute(
574
			'files_sharing.sharecontroller.showShare',
575
			['token' => $token]
576
		);
577
		$author = $share['uid_initiator'];
578
579
		$filename = basename($share['file_target']);
580
581
		return [
582
			'author'   => $author,
583
			'link'     => $link,
584
			'password' => $password,
585
			'filename' => $filename
586
		];
587
	}
588
589
590
	/**
591
	 * @param $author
592
	 * @param string $circleName
593
	 *
594
	 * @return IEMailTemplate
595
	 * @throws Exception
596
	 */
597
	protected function generateMailExitingShares($author, $circleName) {
598
		$this->logger->log(
599
			0, "Generating mail about existing share mail from '" . $author . "' in "
600
			   . $circleName
601
		);
602
603
		$emailTemplate = $this->mailer->createEMailTemplate('circles.ExistingShareNotification', []);
604
		$emailTemplate->addHeader();
605
606
		$text = $this->l10n->t('%s shared multiple files with \'%s\'.', [$author, $circleName]);
607
		$emailTemplate->addBodyText(htmlspecialchars($text), $text);
608
609
		return $emailTemplate;
610
	}
611
612
613
	/**
614
	 * @param IEMailTemplate $emailTemplate
615
	 * @param array $data
616
	 */
617
	protected function fillMailExistingShares(IEMailTemplate $emailTemplate, array $data) {
618
		foreach ($data as $item) {
619
//			$text = $this->l10n->t('%s shared »%s« with you.', [$item['author'], $item['filename']]);
620
//			$emailTemplate->addBodyText(
621
//				htmlspecialchars($text) . '<br>' . htmlspecialchars(
622
//					$this->l10n->t('Click the button below to open it.')
623
//				), $text
624
//			);
625
			$emailTemplate->addBodyButton(
626
				$this->l10n->t('Open »%s«', [htmlspecialchars($item['filename'])]), $item['link']
627
			);
628
		}
629
	}
630
631
632
	/**
633
	 * @param IEMailTemplate $emailTemplate
634
	 * @param $author
635
	 * @param $recipient
636
	 *
637
	 * @throws Exception
638
	 */
639
	protected function sendMailExistingShares(IEMailTemplate $emailTemplate, $author, $recipient) {
640
		$subject = $this->l10n->t('%s shared multiple files with you.', [$author]);
641
//		$emailTemplate->addHeading($subject, false);
642
643
		$instanceName = $this->defaults->getName();
644
		$senderName = $this->l10n->t('%s on %s', [$author, $instanceName]);
645
646
		$message = $this->mailer->createMessage();
647
648
		$message->setFrom([Util::getDefaultEmailAddress($instanceName) => $senderName]);
649
		$message->setSubject($subject);
650
		$message->setPlainBody($emailTemplate->renderText());
651
		$message->setHtmlBody($emailTemplate->renderHtml());
652
		$message->setTo([$recipient]);
653
654
		$this->mailer->send($message);
655
656
657
//		$message = $this->mailer->createMessage();
658
//
659
		//
660
		//
661
		//
662
663
664
//		$filename = $share->getNode()
665
//						  ->getName();
666
//		$initiator = $share->getSharedBy();
667
//		$shareWith = $share->getSharedWith();
668
//
669
//		$initiatorUser = $this->userManager->get($initiator);
670
//		$initiatorDisplayName =
671
//			($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
672
//		$initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
673
674
//		$plainBodyPart = $this->l10n->t(
675
//			"%1\$s shared »%2\$s« with you.\nYou should have already received a separate mail with a link to access it.\n",
676
//			[$initiatorDisplayName, $filename]
677
//		);
678
//		$htmlBodyPart = $this->l10n->t(
679
//			'%1$s shared »%2$s« with you. You should have already received a separate mail with a link to access it.',
680
//			[$initiatorDisplayName, $filename]
681
//		);
682
//
683
//		$emailTemplate = $this->mailer->createEMailTemplate(
684
//			'sharebymail.RecipientPasswordNotification', [
685
//														   'filename'       => $filename,
686
//														   'password'       => $password,
687
//														   'initiator'      => $initiatorDisplayName,
688
//														   'initiatorEmail' => $initiatorEmailAddress,
689
//														   'shareWith'      => $shareWith,
690
//													   ]
691
//		);
692
//
693
//		$emailTemplate->setSubject(
694
//			$this->l10n->t(
695
//				'Password to access »%1$s« shared to you by %2$s', [$filename, $initiatorDisplayName]
696
//			)
697
//		);
698
//		$emailTemplate->addHeader();
699
//		$emailTemplate->addHeading($this->l10n->t('Password to access »%s«', [$filename]), false);
700
//		$emailTemplate->addBodyText(htmlspecialchars($htmlBodyPart), $plainBodyPart);
701
//		$emailTemplate->addBodyText($this->l10n->t('It is protected with the following password:'));
702
//		$emailTemplate->addBodyText($password);
703
704
		// The "From" contains the sharers name
705
//		$instanceName = $this->defaults->getName();
706
//		$senderName = $this->l10n->t(
707
//			'%1$s via %2$s',
708
//			[
709
//				$initiatorDisplayName,
710
//				$instanceName
711
//			]
712
//		);
713
//		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
714
//		if ($initiatorEmailAddress !== null) {
715
//			$message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
716
//			$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
717
//		} else {
718
//			$emailTemplate->addFooter();
719
//		}
720
//
721
//		$message->setTo([$email]);
722
//		$message->useTemplate($emailTemplate);
723
//		$this->mailer->send($message);
724
	}
725
726
727
}
728