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

FileSharingBroadcaster::editShareToCircle()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
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\Federation\CloudFederationFactory;
33
use OC\Share20\Share;
34
use OCA\Circles\AppInfo\Application;
35
use OCA\Circles\Db\SharesRequest;
36
use OCA\Circles\Db\TokensRequest;
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 cloudFederationFactory */
79
	private $federationFactory;
80
81
	/** @var ILogger */
82
	private $logger;
83
84
	/** @var Defaults */
85
	private $defaults;
86
87
	/** @var IURLGenerator */
88
	private $urlGenerator;
89
90
	/** @var SharesRequest */
91
	private $sharesRequest;
92
93
	/** @var TokensRequest */
94
	private $tokensRequest;
95
96
	/** @var ConfigService */
97
	private $configService;
98
99
	/** @var MiscService */
100
	private $miscService;
101
102
103
	/**
104
	 * {@inheritdoc}
105
	 */
106
	public function init() {
107
		if ($this->initiated) {
108
			return;
109
		}
110
111
		$this->initiated = true;
112
		$this->l10n = OC::$server->getL10N(Application::APP_NAME);
113
		$this->mailer = OC::$server->getMailer();
114
		$this->rootFolder = OC::$server->getLazyRootFolder();
115
		$this->userManager = OC::$server->getUserManager();
116
		$this->federationFactory = OC::$server->getCloudFederationFactory();
117
		$this->logger = OC::$server->getLogger();
118
		$this->urlGenerator = OC::$server->getURLGenerator();
119
		try {
120
			$this->defaults = OC::$server->query(Defaults::class);
121
			$this->sharesRequest = OC::$server->query(SharesRequest::class);
122
			$this->tokensRequest = OC::$server->query(TokensRequest::class);
123
			$this->configService = OC::$server->query(ConfigService::class);
124
			$this->miscService = OC::$server->query(MiscService::class);
125
		} 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...
126
			\OC::$server->getLogger()
127
						->log(1, 'Circles: cannot init FileSharingBroadcaster - ' . $e->getMessage());
128
		}
129
	}
130
131
132
	/**
133
	 * {@inheritdoc}
134
	 */
135
	public function end() {
136
	}
137
138
139
	/**
140
	 * {@inheritdoc}
141
	 */
142
	public function createShareToCircle(SharingFrame $frame, Circle $circle) {
143
		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...
144
			return false;
145
		}
146
147
		return true;
148
	}
149
150
151
	/**
152
	 * {@inheritdoc}
153
	 */
154
	public function deleteShareToCircle(SharingFrame $frame, Circle $circle) {
155
		return true;
156
	}
157
158
159
	/**
160
	 * {@inheritdoc}
161
	 */
162
	public function editShareToCircle(SharingFrame $frame, Circle $circle) {
163
		return true;
164
	}
165
166
167
	/**
168
	 * {@inheritdoc}
169
	 * @throws IllegalIDChangeException
170
	 */
171
	public function createShareToMember(SharingFrame $frame, Member $member) {
172
		if (!$frame->is0Circle()) {
173
			return false;
174
		}
175
176
		$payload = $frame->getPayload();
177
		if (!key_exists('share', $payload)) {
178
			return false;
179
		}
180
181
		$share = $this->generateShare($payload['share']);
182
		if ($member->getType() === Member::TYPE_MAIL || $member->getType() === Member::TYPE_CONTACT) {
183
			try {
184
				$circle = $frame->getCircle();
185
186
				// federated shared in contact
187
				$clouds = $this->getCloudsFromContact($member->getUserId());
188
				if (!empty($clouds)) {
189
					foreach ($clouds as $cloudId) {
190
						$this->sharedByFederated($circle, $share, $cloudId);
0 ignored issues
show
Unused Code introduced by
The call to the method OCA\Circles\Circles\File...er::sharedByFederated() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
191
					}
192
193
					return true;
194
				}
195
196
				$password = '';
197
				if ($this->configService->enforcePasswordProtection()) {
198
					$password = $this->miscService->token(15);
199
				}
200
201
				$token = $this->tokensRequest->generateTokenForMember($member, $share->getId(), $password);
202
				if ($token !== '') {
203
					$mails = [$member->getUserId()];
204
					if ($member->getType() === Member::TYPE_CONTACT) {
205
						$mails = $this->getMailsFromContact($member->getUserId());
206
					}
207
208
					foreach ($mails as $mail) {
209
						$this->sharedByMail($circle, $share, $mail, $token, $password);
210
					}
211
				}
212
			} catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
213
			}
214
		}
215
216
		return true;
217
	}
218
219
220
	/**
221
	 * {@inheritdoc}
222
	 */
223
	public function deleteShareToMember(SharingFrame $frame, Member $member) {
224
		return true;
225
	}
226
227
228
	/**
229
	 * {@inheritdoc}
230
	 */
231
	public function editShareToMember(SharingFrame $frame, Member $member) {
232
		return true;
233
	}
234
235
236
	/**
237
	 * @param Circle $circle
238
	 * @param Member $member
239
	 */
240
	public function sendMailAboutExistingShares(Circle $circle, Member $member) {
241
		$this->init();
242
		if ($member->getType() !== Member::TYPE_MAIL && $member->getType() !== Member::TYPE_CONTACT) {
243
			return;
244
		}
245
246
		// TODO: check that contact got cloudIds. if so, generate shares to federated cloud Id;
247
248
		$allShares = $this->sharesRequest->getSharesForCircle($member->getCircleId());
249
		$knownShares = array_map(
250
			function(SharesToken $shareToken) {
251
				return $shareToken->getShareId();
252
			},
253
			$this->tokensRequest->getTokensFromMember($member)
254
		);
255
256
		$unknownShares = [];
257
		foreach ($allShares as $share) {
258
			if (!in_array($share['id'], $knownShares)) {
259
				$unknownShares[] = $share;
260
			}
261
		}
262
263
		$author = $circle->getViewer()
264
						 ->getUserId();
265
		$this->sendMailExitingShares(
266
			$unknownShares, MiscService::getDisplay($author, Member::TYPE_USER), $member, $circle->getName()
267
		);
268
	}
269
270
271
	/**
272
	 * recreate the share from the JSON payload.
273
	 *
274
	 * @param array $data
275
	 *
276
	 * @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...
277
	 * @throws IllegalIDChangeException
278
	 */
279
	private function generateShare($data) {
280
		$this->logger->log(0, 'Regenerate shares from payload: ' . json_encode($data));
281
282
		$share = new Share($this->rootFolder, $this->userManager);
283
		$share->setId($data['id']);
284
		$share->setSharedBy($data['sharedBy']);
285
		$share->setSharedWith($data['sharedWith']);
286
		$share->setNodeId($data['nodeId']);
287
		$share->setShareOwner($data['shareOwner']);
288
		$share->setPermissions($data['permissions']);
289
		$share->setToken($data['token']);
290
		$share->setPassword($data['password']);
291
292
		return $share;
293
	}
294
295
296
	/**
297
	 * @param Circle $circle
298
	 * @param IShare $share
299
	 * @param $cloudId
300
	 */
301
	private function sharedByFederated(Circle $circle, IShare $share, $cloudId) {
0 ignored issues
show
Unused Code introduced by
The parameter $circle is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $share is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $cloudId is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
302
		// TODO: Generate a Federated Share to the cloudId.
303
	}
304
305
306
	/**
307
	 * @param Circle $circle
308
	 * @param IShare $share
309
	 * @param string $email
310
	 * @param string $token
311
	 * @param string $password
312
	 */
313
	private function sharedByMail(Circle $circle, IShare $share, $email, $token, $password) {
314
		// genelink
315
		$link = $this->urlGenerator->linkToRouteAbsolute(
316
			'files_sharing.sharecontroller.showShare',
317
			['token' => $token]
318
		);
319
320
		try {
321
			$this->sendMail(
322
				$share->getNode()
323
					  ->getName(), $link,
324
				MiscService::getDisplay($share->getSharedBy(), Member::TYPE_USER),
325
				$circle->getName(), $email
326
			);
327
			$this->sendPasswordByMail(
328
				$share, MiscService::getDisplay($share->getSharedBy(), Member::TYPE_USER),
329
				$email, $password
330
			);
331
		} catch (Exception $e) {
332
			OC::$server->getLogger()
333
					   ->log(1, 'Circles::sharedByMail - mail were not sent: ' . $e->getMessage());
334
		}
335
	}
336
337
338
	/**
339
	 * @param $fileName
340
	 * @param string $link
341
	 * @param string $author
342
	 * @param $circleName
343
	 * @param string $email
344
	 *
345
	 * @throws Exception
346
	 */
347
	protected function sendMail($fileName, $link, $author, $circleName, $email) {
348
		$message = $this->mailer->createMessage();
349
350
		$this->logger->log(
351
			0, "Sending mail to circle '" . $circleName . "': " . $email . ' file: ' . $fileName
352
			   . ' - link: ' . $link
353
		);
354
355
		$subject = $this->l10n->t('%s shared »%s« with you.', [$author, $fileName]);
356
		$text = $this->l10n->t('%s shared »%s« with \'%s\'.', [$author, $fileName, $circleName]);
357
358
		$emailTemplate =
359
			$this->generateEmailTemplate($subject, $text, $fileName, $link, $author, $circleName);
360
361
		$instanceName = $this->defaults->getName();
362
		$senderName = $this->l10n->t('%s on %s', [$author, $instanceName]);
363
364
		$message->setFrom([Util::getDefaultEmailAddress($instanceName) => $senderName]);
365
		$message->setSubject($subject);
366
		$message->setPlainBody($emailTemplate->renderText());
367
		$message->setHtmlBody($emailTemplate->renderHtml());
368
		$message->setTo([$email]);
369
370
		$this->mailer->send($message);
371
	}
372
373
374
	/**
375
	 * @param IShare $share
376
	 * @param string $circleName
377
	 * @param string $email
378
	 *
379
	 * @param $password
380
	 *
381
	 * @throws NotFoundException
382
	 * @throws Exception
383
	 */
384
	protected function sendPasswordByMail(IShare $share, $circleName, $email, $password) {
385
		if (!$this->configService->sendPasswordByMail() || $password === '') {
386
			return;
387
		}
388
389
		$message = $this->mailer->createMessage();
390
391
		$this->logger->log(0, "Sending password mail to circle '" . $circleName . "': " . $email);
392
393
		$filename = $share->getNode()
394
						  ->getName();
395
		$initiator = $share->getSharedBy();
396
		$shareWith = $share->getSharedWith();
397
398
		$initiatorUser = $this->userManager->get($initiator);
399
		$initiatorDisplayName =
400
			($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...
401
		$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...
402
403
		$plainBodyPart = $this->l10n->t(
404
			"%1\$s shared »%2\$s« with you.\nYou should have already received a separate mail with a link to access it.\n",
405
			[$initiatorDisplayName, $filename]
406
		);
407
		$htmlBodyPart = $this->l10n->t(
408
			'%1$s shared »%2$s« with you. You should have already received a separate mail with a link to access it.',
409
			[$initiatorDisplayName, $filename]
410
		);
411
412
		$emailTemplate = $this->mailer->createEMailTemplate(
413
			'sharebymail.RecipientPasswordNotification', [
414
														   'filename'       => $filename,
415
														   'password'       => $password,
416
														   'initiator'      => $initiatorDisplayName,
417
														   'initiatorEmail' => $initiatorEmailAddress,
418
														   'shareWith'      => $shareWith,
419
													   ]
420
		);
421
422
		$emailTemplate->setSubject(
423
			$this->l10n->t(
424
				'Password to access »%1$s« shared to you by %2$s', [$filename, $initiatorDisplayName]
425
			)
426
		);
427
		$emailTemplate->addHeader();
428
		$emailTemplate->addHeading($this->l10n->t('Password to access »%s«', [$filename]), false);
429
		$emailTemplate->addBodyText(htmlspecialchars($htmlBodyPart), $plainBodyPart);
430
		$emailTemplate->addBodyText($this->l10n->t('It is protected with the following password:'));
431
		$emailTemplate->addBodyText($password);
432
433
		// The "From" contains the sharers name
434
		$instanceName = $this->defaults->getName();
435
		$senderName = $this->l10n->t(
436
			'%1$s via %2$s',
437
			[
438
				$initiatorDisplayName,
439
				$instanceName
440
			]
441
		);
442
		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
443 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...
444
			$message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
445
			$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
446
		} else {
447
			$emailTemplate->addFooter();
448
		}
449
450
		$message->setTo([$email]);
451
		$message->useTemplate($emailTemplate);
452
		$this->mailer->send($message);
453
	}
454
455
456
	/**
457
	 * @param $subject
458
	 * @param $text
459
	 * @param $fileName
460
	 * @param $link
461
	 * @param string $author
462
	 * @param string $circleName
463
	 *
464
	 * @return IEMailTemplate
465
	 */
466
	private function generateEmailTemplate($subject, $text, $fileName, $link, $author, $circleName
467
	) {
468
		$emailTemplate = $this->mailer->createEMailTemplate(
469
			'circles.ShareNotification', [
470
										   'fileName'   => $fileName,
471
										   'fileLink'   => $link,
472
										   'author'     => $author,
473
										   'circleName' => $circleName,
474
									   ]
475
		);
476
477
		$emailTemplate->addHeader();
478
		$emailTemplate->addHeading($subject, false);
479
		$emailTemplate->addBodyText(
480
			htmlspecialchars($text) . '<br>' . htmlspecialchars(
481
				$this->l10n->t('Click the button below to open it.')
482
			), $text
483
		);
484
		$emailTemplate->addBodyButton(
485
			$this->l10n->t('Open »%s«', [htmlspecialchars($fileName)]), $link
486
		);
487
488
		return $emailTemplate;
489
	}
490
491
492
	/**
493
	 * @param array $unknownShares
494
	 * @param string $author
495
	 * @param Member $member
496
	 * @param string $circleName
497
	 */
498
	private function sendMailExitingShares(array $unknownShares, $author, Member $member, $circleName) {
499
		$password = '';
500
		if ($this->configService->enforcePasswordProtection()) {
501
			try {
502
				$password = $this->miscService->token(15);
503
			} catch (Exception $e) {
504
				return;
505
			}
506
		}
507
508
		$data = [];
509
		foreach ($unknownShares as $share) {
510
			$data[] = $this->getMailLinkFromShare($share, $member, $password);
511
		}
512
513
514
		if (sizeof($data) === 0) {
515
			return;
516
		}
517
518
		try {
519
			$template = $this->generateMailExitingShares($author, $circleName);
520
			$this->fillMailExistingShares($template, $data);
521
			$this->sendMailExistingShares($template, $author, $member->getUserId());
522
			$this->sendPasswordExistingShares($author, $member->getUserId(), $password);
523
		} catch (Exception $e) {
524
			$this->logger->log(2, 'Failed to send mail about existing share ' . $e->getMessage());
525
		}
526
	}
527
528
529
	/**
530
	 * @param $author
531
	 * @param string $email
532
	 *
533
	 * @param $password
534
	 *
535
	 * @throws Exception
536
	 */
537
	protected function sendPasswordExistingShares($author, $email, $password) {
538
		if (!$this->configService->sendPasswordByMail() || $password === '') {
539
			return;
540
		}
541
542
		$message = $this->mailer->createMessage();
543
544
		$authorUser = $this->userManager->get($author);
545
		$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...
546
		$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...
547
548
		$this->logger->log(0, "Sending password mail about existing files to '" . $email . "'");
549
550
		$plainBodyPart = $this->l10n->t(
551
			"%1\$s shared multiple files with you.\nYou should have already received a separate mail with a link to access them.\n",
552
			[$authorName]
553
		);
554
		$htmlBodyPart = $this->l10n->t(
555
			'%1$s shared multiple files with you. You should have already received a separate mail with a link to access them.',
556
			[$authorName]
557
		);
558
559
		$emailTemplate = $this->mailer->createEMailTemplate(
560
			'sharebymail.RecipientPasswordNotification', [
561
														   'password' => $password,
562
														   'author'   => $author
563
													   ]
564
		);
565
566
		$emailTemplate->setSubject(
567
			$this->l10n->t(
568
				'Password to access files shared to you by %1$s', [$authorName]
569
			)
570
		);
571
		$emailTemplate->addHeader();
572
		$emailTemplate->addHeading($this->l10n->t('Password to access files'), false);
573
		$emailTemplate->addBodyText(htmlspecialchars($htmlBodyPart), $plainBodyPart);
574
		$emailTemplate->addBodyText($this->l10n->t('It is protected with the following password:'));
575
		$emailTemplate->addBodyText($password);
576
577
		// The "From" contains the sharers name
578
		$instanceName = $this->defaults->getName();
579
		$senderName = $this->l10n->t(
580
			'%1$s via %2$s',
581
			[
582
				$authorName,
583
				$instanceName
584
			]
585
		);
586
587
		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
588 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...
589
			$message->setReplyTo([$authorEmail => $authorName]);
590
			$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
591
		} else {
592
			$emailTemplate->addFooter();
593
		}
594
595
		$message->setTo([$email]);
596
		$message->useTemplate($emailTemplate);
597
		$this->mailer->send($message);
598
	}
599
600
	/**
601
	 * @param array $share
602
	 * @param Member $member
603
	 * @param string $password
604
	 *
605
	 * @return array
606
	 */
607
	private function getMailLinkFromShare(array $share, Member $member, $password) {
608
		$token = $this->tokensRequest->generateTokenForMember($member, $share['id'], $password);
609
		$link = $this->urlGenerator->linkToRouteAbsolute(
610
			'files_sharing.sharecontroller.showShare',
611
			['token' => $token]
612
		);
613
		$author = $share['uid_initiator'];
614
615
		$filename = basename($share['file_target']);
616
617
		return [
618
			'author'   => $author,
619
			'link'     => $link,
620
			'password' => $password,
621
			'filename' => $filename
622
		];
623
	}
624
625
626
	/**
627
	 * @param $author
628
	 * @param string $circleName
629
	 *
630
	 * @return IEMailTemplate
631
	 * @throws Exception
632
	 */
633
	protected function generateMailExitingShares($author, $circleName) {
634
		$this->logger->log(
635
			0, "Generating mail about existing share mail from '" . $author . "' in "
636
			   . $circleName
637
		);
638
639
		$emailTemplate = $this->mailer->createEMailTemplate('circles.ExistingShareNotification', []);
640
		$emailTemplate->addHeader();
641
642
		$text = $this->l10n->t('%s shared multiple files with \'%s\'.', [$author, $circleName]);
643
		$emailTemplate->addBodyText(htmlspecialchars($text), $text);
644
645
		return $emailTemplate;
646
	}
647
648
649
	/**
650
	 * @param IEMailTemplate $emailTemplate
651
	 * @param array $data
652
	 */
653
	protected function fillMailExistingShares(IEMailTemplate $emailTemplate, array $data) {
654
		foreach ($data as $item) {
655
//			$text = $this->l10n->t('%s shared »%s« with you.', [$item['author'], $item['filename']]);
656
//			$emailTemplate->addBodyText(
657
//				htmlspecialchars($text) . '<br>' . htmlspecialchars(
658
//					$this->l10n->t('Click the button below to open it.')
659
//				), $text
660
//			);
661
			$emailTemplate->addBodyButton(
662
				$this->l10n->t('Open »%s«', [htmlspecialchars($item['filename'])]), $item['link']
663
			);
664
		}
665
	}
666
667
668
	/**
669
	 * @param IEMailTemplate $emailTemplate
670
	 * @param $author
671
	 * @param $recipient
672
	 *
673
	 * @throws Exception
674
	 */
675
	protected function sendMailExistingShares(IEMailTemplate $emailTemplate, $author, $recipient) {
676
		$subject = $this->l10n->t('%s shared multiple files with you.', [$author]);
677
//		$emailTemplate->addHeading($subject, false);
678
679
		$instanceName = $this->defaults->getName();
680
		$senderName = $this->l10n->t('%s on %s', [$author, $instanceName]);
681
682
		$message = $this->mailer->createMessage();
683
684
		$message->setFrom([Util::getDefaultEmailAddress($instanceName) => $senderName]);
685
		$message->setSubject($subject);
686
		$message->setPlainBody($emailTemplate->renderText());
687
		$message->setHtmlBody($emailTemplate->renderHtml());
688
		$message->setTo([$recipient]);
689
690
		$this->mailer->send($message);
691
692
693
//		$message = $this->mailer->createMessage();
694
//
695
		//
696
		//
697
		//
698
699
700
//		$filename = $share->getNode()
701
//						  ->getName();
702
//		$initiator = $share->getSharedBy();
703
//		$shareWith = $share->getSharedWith();
704
//
705
//		$initiatorUser = $this->userManager->get($initiator);
706
//		$initiatorDisplayName =
707
//			($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
708
//		$initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
709
710
//		$plainBodyPart = $this->l10n->t(
711
//			"%1\$s shared »%2\$s« with you.\nYou should have already received a separate mail with a link to access it.\n",
712
//			[$initiatorDisplayName, $filename]
713
//		);
714
//		$htmlBodyPart = $this->l10n->t(
715
//			'%1$s shared »%2$s« with you. You should have already received a separate mail with a link to access it.',
716
//			[$initiatorDisplayName, $filename]
717
//		);
718
//
719
//		$emailTemplate = $this->mailer->createEMailTemplate(
720
//			'sharebymail.RecipientPasswordNotification', [
721
//														   'filename'       => $filename,
722
//														   'password'       => $password,
723
//														   'initiator'      => $initiatorDisplayName,
724
//														   'initiatorEmail' => $initiatorEmailAddress,
725
//														   'shareWith'      => $shareWith,
726
//													   ]
727
//		);
728
//
729
//		$emailTemplate->setSubject(
730
//			$this->l10n->t(
731
//				'Password to access »%1$s« shared to you by %2$s', [$filename, $initiatorDisplayName]
732
//			)
733
//		);
734
//		$emailTemplate->addHeader();
735
//		$emailTemplate->addHeading($this->l10n->t('Password to access »%s«', [$filename]), false);
736
//		$emailTemplate->addBodyText(htmlspecialchars($htmlBodyPart), $plainBodyPart);
737
//		$emailTemplate->addBodyText($this->l10n->t('It is protected with the following password:'));
738
//		$emailTemplate->addBodyText($password);
739
740
		// The "From" contains the sharers name
741
//		$instanceName = $this->defaults->getName();
742
//		$senderName = $this->l10n->t(
743
//			'%1$s via %2$s',
744
//			[
745
//				$initiatorDisplayName,
746
//				$instanceName
747
//			]
748
//		);
749
//		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
750
//		if ($initiatorEmailAddress !== null) {
751
//			$message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
752
//			$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
753
//		} else {
754
//			$emailTemplate->addFooter();
755
//		}
756
//
757
//		$message->setTo([$email]);
758
//		$message->useTemplate($emailTemplate);
759
//		$this->mailer->send($message);
760
	}
761
762
763
	/**
764
	 * @param string $contactId
765
	 *
766
	 * @return array
767
	 */
768 View Code Duplication
	private function getCloudsFromContact(string $contactId): array {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
769
		$contact = MiscService::getContactData($contactId);
770
		if (!key_exists('CLOUD', $contact)) {
771
			return [];
772
		}
773
774
		return $contact['CLOUD'];
775
	}
776
777
	/**
778
	 * @param string $contactId
779
	 *
780
	 * @return array
781
	 */
782 View Code Duplication
	private function getMailsFromContact(string $contactId): array {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
783
		$contact = MiscService::getContactData($contactId);
784
		if (!key_exists('EMAIL', $contact)) {
785
			return [];
786
		}
787
788
		return $contact['EMAIL'];
789
	}
790
791
}
792