Completed
Pull Request — master (#551)
by Maxence
02:35
created

MemberAdd::manage()   A

Complexity

Conditions 3
Paths 5

Size

Total Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 44
rs 9.216
c 0
b 0
f 0
cc 3
nc 5
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
6
/**
7
 * Circles - Bring cloud-users closer together.
8
 *
9
 * This file is licensed under the Affero General Public License version 3 or
10
 * later. See the COPYING file.
11
 *
12
 * @author Maxence Lange <[email protected]>
13
 * @copyright 2021
14
 * @license GNU AGPL version 3 or any later version
15
 *
16
 * This program is free software: you can redistribute it and/or modify
17
 * it under the terms of the GNU Affero General Public License as
18
 * published by the Free Software Foundation, either version 3 of the
19
 * License, or (at your option) any later version.
20
 *
21
 * This program is distributed in the hope that it will be useful,
22
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24
 * GNU Affero General Public License for more details.
25
 *
26
 * You should have received a copy of the GNU Affero General Public License
27
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
28
 *
29
 */
30
31
32
namespace OCA\Circles\FederatedItems;
33
34
35
use daita\MySmallPhpTools\Exceptions\InvalidItemException;
36
use daita\MySmallPhpTools\Exceptions\RequestNetworkException;
37
use daita\MySmallPhpTools\Exceptions\SignatoryException;
38
use daita\MySmallPhpTools\Traits\Nextcloud\nc21\TNC21Logger;
39
use daita\MySmallPhpTools\Traits\TStringTools;
40
use Exception;
41
use OC\User\NoUserException;
42
use OCA\Circles\Db\MemberRequest;
43
use OCA\Circles\Exceptions\CircleNotFoundException;
44
use OCA\Circles\Exceptions\FederatedUserException;
45
use OCA\Circles\Exceptions\FederatedUserNotFoundException;
46
use OCA\Circles\Exceptions\InvalidIdException;
47
use OCA\Circles\Exceptions\MemberAlreadyExistsException;
48
use OCA\Circles\Exceptions\MemberNotFoundException;
49
use OCA\Circles\Exceptions\MembersLimitException;
50
use OCA\Circles\Exceptions\MemberTypeNotFoundException;
51
use OCA\Circles\Exceptions\OwnerNotFoundException;
52
use OCA\Circles\Exceptions\RemoteInstanceException;
53
use OCA\Circles\Exceptions\RemoteNotFoundException;
54
use OCA\Circles\Exceptions\RemoteResourceNotFoundException;
55
use OCA\Circles\Exceptions\TokenDoesNotExistException;
56
use OCA\Circles\Exceptions\UnknownRemoteException;
57
use OCA\Circles\Exceptions\UserTypeNotFoundException;
58
use OCA\Circles\IFederatedItem;
59
use OCA\Circles\IFederatedItemAsync;
60
use OCA\Circles\IFederatedItemMemberCheckNotRequired;
61
use OCA\Circles\IFederatedItemMemberRequired;
62
use OCA\Circles\IFederatedUser;
63
use OCA\Circles\Model\DeprecatedCircle;
64
use OCA\Circles\Model\DeprecatedMember;
65
use OCA\Circles\Model\Federated\FederatedEvent;
66
use OCA\Circles\Model\FederatedUser;
67
use OCA\Circles\Model\Helpers\MemberHelper;
68
use OCA\Circles\Model\ManagedModel;
69
use OCA\Circles\Model\Member;
70
use OCA\Circles\Model\SharesToken;
71
use OCA\Circles\Service\CircleService;
72
use OCA\Circles\Service\ConfigService;
73
use OCA\Circles\Service\FederatedUserService;
74
use OCP\IUser;
75
use OCP\IUserManager;
76
use OCP\Mail\IEMailTemplate;
77
use OCP\Util;
78
79
80
/**
81
 * Class MemberAdd
82
 *
83
 * @package OCA\Circles\GlobalScale
84
 */
85
class MemberAdd implements
86
	IFederatedItem,
87
	IFederatedItemAsync,
88
	IFederatedItemMemberRequired,
89
	IFederatedItemMemberCheckNotRequired {
90
91
92
	use TStringTools;
93
	use TNC21Logger;
94
95
96
	/** @var IUserManager */
97
	private $userManager;
98
99
	/** @var FederatedUserService */
100
	private $federatedUserService;
101
102
	/** @var MemberRequest */
103
	private $memberRequest;
104
105
	/** @var CircleService */
106
	private $circleService;
107
108
	/** @var ConfigService */
109
	private $configService;
110
111
112
	/**
113
	 * MemberAdd constructor.
114
	 *
115
	 * @param IUserManager $userManager
116
	 * @param FederatedUserService $federatedUserService
117
	 * @param MemberRequest $memberRequest
118
	 * @param CircleService $circleService
119
	 * @param ConfigService $configService
120
	 */
121 View Code Duplication
	public function __construct(
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...
122
		IUserManager $userManager, FederatedUserService $federatedUserService, MemberRequest $memberRequest,
123
		CircleService $circleService, ConfigService $configService
124
	) {
125
		$this->userManager = $userManager;
126
		$this->federatedUserService = $federatedUserService;
127
		$this->memberRequest = $memberRequest;
128
		$this->circleService = $circleService;
129
		$this->configService = $configService;
130
	}
131
132
133
	/**
134
	 * @param FederatedEvent $event
135
	 *
136
	 * @throws CircleNotFoundException
137
	 * @throws FederatedUserException
138
	 * @throws FederatedUserNotFoundException
139
	 * @throws InvalidIdException
140
	 * @throws InvalidItemException
141
	 * @throws MemberAlreadyExistsException
142
	 * @throws MembersLimitException
143
	 * @throws OwnerNotFoundException
144
	 * @throws RemoteInstanceException
145
	 * @throws RemoteNotFoundException
146
	 * @throws RemoteResourceNotFoundException
147
	 * @throws RequestNetworkException
148
	 * @throws SignatoryException
149
	 * @throws UnknownRemoteException
150
	 * @throws UserTypeNotFoundException
151
	 */
152
	public function verify(FederatedEvent $event): void {
153
		$member = $event->getMember();
154
		$circle = $event->getCircle();
155
		$initiator = $circle->getInitiator();
156
157
		$member->setCircleId($circle->getId());
158
159
		$initiatorHelper = new MemberHelper($initiator);
160
		$initiatorHelper->mustBeModerator();
161
162
		try {
163
			$knownMember = $this->memberRequest->searchMember($member);
0 ignored issues
show
Unused Code introduced by
$knownMember is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
164
			// TODO: maybe member is requesting access
165
			// TODO: check if it is a member or a mail or a circle and fix the returned message
166
			throw new MemberAlreadyExistsException(
167
				'Member %s already exists', ['member' => $member->getUserId()]
168
			);
169
		} catch (MemberNotFoundException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
170
		}
171
172
		$federatedId = $member->getUserId() . '@' . $member->getInstance();
173
		$federatedUser = $this->federatedUserService->getFederatedUser($federatedId, $member->getUserType());
174
		$member->importFromIFederatedUser($federatedUser);
175
		$member->setId($this->uuid(ManagedModel::ID_LENGTH));
176
177
		// TODO: check Config on Circle to know if we set Level to 1 or just send an invitation
178
		$member->setLevel(Member::LEVEL_MEMBER);
179
		$member->setStatus(Member::STATUS_MEMBER);
180
		$event->setDataOutcome(['member' => $member]);
181
182
		// TODO: Managing cached name
183
		//		$member->setCachedName($eventMember->getCachedName());
184
		$this->circleService->confirmCircleNotFull($circle);
185
186
		// TODO: check if it is a member or a mail or a circle and fix the returned message
187
		$event->setReadingOutcome('Member %s have been added to Circle', ['userId' => $member->getUserId()]);
188
189
		return;
190
191
192
//		$member = $this->membersRequest->getFreshNewMember(
193
//			$circle->getUniqueId(), $ident, $eventMember->getType(), $eventMember->getInstance()
194
//		);
195
//		$member->hasToBeInviteAble()
196
//
197
//		$this->membersService->addMemberBasedOnItsType($circle, $member);
198
//
199
//		$password = '';
200
//		$sendPasswordByMail = false;
201
//		if ($this->configService->enforcePasswordProtection($circle)) {
202
//			if ($circle->getSetting('password_single_enabled') === 'true') {
203
//				$password = $circle->getPasswordSingle();
204
//			} else {
205
//				$sendPasswordByMail = true;
206
//				$password = $this->miscService->token(15);
207
//			}
208
//		}
209
//
210
//		$event->setData(
211
//			new SimpleDataStore(
212
//				[
213
//					'password'       => $password,
214
//					'passwordByMail' => $sendPasswordByMail
215
//				]
216
//			)
217
//		);
218
	}
219
220
221
	/**
222
	 * @param FederatedEvent $event
223
	 *
224
	 * @throws InvalidIdException
225
	 */
226
	public function manage(FederatedEvent $event): void {
227
		$member = $event->getMember();
228
229
		try {
230
			$this->memberRequest->getMember($member->getId());
231
232
			return;
233
		} catch (MemberNotFoundException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
234
		}
235
236
		try {
237
			$federatedUser = new FederatedUser();
238
			$federatedUser->importFromIFederatedUser($member);
239
			$this->federatedUserService->confirmLocalSingleId($federatedUser);
240
		} catch (FederatedUserException $e) {
241
			$this->e($e, ['member' => $member]);
242
243
			return;
244
		}
245
246
		$this->memberRequest->save($member);
247
248
//
249
//		//
250
//		// TODO: verifiez comment se passe le cached name sur un member_add
251
//		//
252
//		$cachedName = $member->getCachedName();
253
//		$password = $event->getData()
254
//						  ->g('password');
255
//
256
//		$shares = $this->generateUnknownSharesLinks($circle, $member, $password);
257
//		$result = [
258
//			'unknownShares' => $shares,
259
//			'cachedName'    => $cachedName
260
//		];
261
//
262
//		if ($member->getType() === DeprecatedMember::TYPE_CONTACT
263
//			&& $this->configService->isLocalInstance($member->getInstance())) {
264
//			$result['contact'] = $this->miscService->getInfosFromContact($member);
265
//		}
266
//
267
//		$event->setResult(new SimpleDataStore($result));
268
//		$this->eventsService->onMemberNew($circle, $member);
269
	}
270
271
272
	/**
273
	 * @param FederatedEvent[] $events
274
	 *
275
	 * @throws Exception
276
	 */
277
	public function result(array $events): void {
278
//		$password = $cachedName = '';
279
//		$circle = $member = null;
280
//		$links = [];
281
//		$recipients = [];
282
//		foreach ($events as $event) {
283
//			$data = $event->getData();
284
//			if ($data->gBool('passwordByMail') !== false) {
285
//				$password = $data->g('password');
286
//			}
287
//			$circle = $event->getDeprecatedCircle();
288
//			$member = $event->getMember();
289
//			$result = $event->getResult();
290
//			if ($result->g('cachedName') !== '') {
291
//				$cachedName = $result->g('cachedName');
292
//			}
293
//
294
//			$links = array_merge($links, $result->gArray('unknownShares'));
295
//			$contact = $result->gArray('contact');
296
//			if (!empty($contact)) {
297
//				$recipients = $contact['emails'];
298
//			}
299
//		}
300
//
301
//		if (empty($links) || $circle === null || $member === null) {
302
//			return;
303
//		}
304
//
305
//		if ($cachedName !== '') {
306
//			$member->setCachedName($cachedName);
307
//			$this->membersService->updateMember($member);
308
//		}
309
//
310
//		if ($member->getType() === DeprecatedMember::TYPE_MAIL
311
//			|| $member->getType() === DeprecatedMember::TYPE_CONTACT) {
312
//			if ($member->getType() === DeprecatedMember::TYPE_MAIL) {
313
//				$recipients = [$member->getUserId()];
314
//			}
315
//
316
//			foreach ($recipients as $recipient) {
317
//				$this->memberIsMailbox($circle, $recipient, $links, $password);
318
//			}
319
//		}
320
	}
321
322
323
	/**
324
	 * confirm the validity of a UserId, based on UserType.
325
	 *
326
	 * @param IFederatedUser $member
327
	 *
328
	 * @throws FederatedUserException
329
	 * @throws InvalidIdException
330
	 * @throws UserTypeNotFoundException
331
	 * @throws CircleNotFoundException
332
	 * @throws FederatedUserNotFoundException
333
	 * @throws OwnerNotFoundException
334
	 * @throws RemoteInstanceException
335
	 * @throws RemoteNotFoundException
336
	 * @throws RemoteResourceNotFoundException
337
	 * @throws UnknownRemoteException
338
	 * @throws InvalidItemException
339
	 * @throws RequestNetworkException
340
	 * @throws SignatoryException
341
	 */
342
	private function confirmMember(IFederatedUser $member): void {
343
344
		// TODO: confirm SingleId ???
345
//		switch ($member->getUserType()) {
346
//			case Member::TYPE_USER:
347
		$this->federatedUserService->getFederatedUser($member->getUserId(), $member->getUserType());
348
//				break;
349
//
350
//			// TODO: confirm other UserType
351
//			default:
352
//				break;
353
////				throw new UserTypeNotFoundException();
354
//		}
355
	}
356
357
358
	/**
359
	 * @param IFederatedUser $member
360
	 *
361
	 * @throws NoUserException
362
	 */
363
	private function confirmMemberTypeUser(IFederatedUser $member): void {
364
		if ($this->configService->isLocalInstance($member->getInstance())) {
365
			$user = $this->userManager->get($member->getUserId());
366
			if ($user === null) {
367
				throw new NoUserException('user not found');
368
			}
369
370
			$member->setUserId($user->getUID());
371
372
			return;
373
		}
374
375
		// TODO #M002: request the remote instance and check that user exists
376
	}
377
378
//	/**
379
//	 * Verify if a local account is valid.
380
//	 *
381
//	 * @param $ident
382
//	 * @param $type
383
//	 *
384
//	 * @param string $instance
385
//	 *
386
//	 * @throws NoUserException
387
//	 */
388
//	private function verifyIdentLocalMember(&$ident, $type, string $instance = '') {
389
//		if ($type !== DeprecatedMember::TYPE_USER) {
390
//			return;
391
//		}
392
//
393
//		if ($instance === '') {
394
//			try {
395
//				$ident = $this->miscService->getRealUserId($ident);
396
//			} catch (NoUserException $e) {
397
//				throw new NoUserException($this->l10n->t("This user does not exist"));
398
//			}
399
//		}
400
//	}
401
//
402
//
403
//	/**
404
//	 * Verify if a mail have a valid format.
405
//	 *
406
//	 * @param string $ident
407
//	 * @param int $type
408
//	 *
409
//	 * @throws EmailAccountInvalidFormatException
410
//	 */
411
//	private function verifyIdentEmailAddress(string $ident, int $type) {
412
//		if ($type !== DeprecatedMember::TYPE_MAIL) {
413
//			return;
414
//		}
415
//
416
//		if ($this->configService->isAccountOnly()) {
417
//			throw new EmailAccountInvalidFormatException(
418
//				$this->l10n->t('You cannot add a mail address as member of your Circle')
419
//			);
420
//		}
421
//
422
//		if (!filter_var($ident, FILTER_VALIDATE_EMAIL)) {
423
//			throw new EmailAccountInvalidFormatException(
424
//				$this->l10n->t('Email format is not valid')
425
//			);
426
//		}
427
//	}
428
//
429
//
430
//	/**
431
//	 * Verify if a contact exist in current user address books.
432
//	 *
433
//	 * @param $ident
434
//	 * @param $type
435
//	 *
436
//	 * @throws NoUserException
437
//	 * @throws EmailAccountInvalidFormatException
438
//	 */
439
//	private function verifyIdentContact(&$ident, $type) {
440
//		if ($type !== DeprecatedMember::TYPE_CONTACT) {
441
//			return;
442
//		}
443
//
444
//		if ($this->configService->isAccountOnly()) {
445
//			throw new EmailAccountInvalidFormatException(
446
//				$this->l10n->t('You cannot add a contact as member of your Circle')
447
//			);
448
//		}
449
//
450
//		$tmpContact = $this->userId . ':' . $ident;
451
//		$result = MiscService::getContactData($tmpContact);
452
//		if (empty($result)) {
453
//			throw new NoUserException($this->l10n->t("This contact is not available"));
454
//		}
455
//
456
//		$ident = $tmpContact;
457
//	}
458
459
460
	/**
461
	 * @param DeprecatedCircle $circle
462
	 * @param string $recipient
463
	 * @param array $links
464
	 * @param string $password
465
	 */
466 View Code Duplication
	private function memberIsMailbox(
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...
467
		DeprecatedCircle $circle, string $recipient, array $links, string $password
468
	) {
469
		if ($circle->getViewer() === null) {
470
			$author = $circle->getOwner()
471
							 ->getUserId();
472
		} else {
473
			$author = $circle->getViewer()
474
							 ->getUserId();
475
		}
476
477
		try {
478
			$template = $this->generateMailExitingShares($author, $circle->getName());
479
			$this->fillMailExistingShares($template, $links);
480
			$this->sendMailExistingShares($template, $author, $recipient);
481
			$this->sendPasswordExistingShares($author, $recipient, $password);
482
		} catch (Exception $e) {
483
			$this->miscService->log('Failed to send mail about existing share ' . $e->getMessage());
0 ignored issues
show
Bug introduced by
The property miscService does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
484
		}
485
	}
486
487
488
	/**
489
	 * @param DeprecatedCircle $circle
490
	 * @param DeprecatedMember $member
491
	 * @param string $password
492
	 *
493
	 * @return array
494
	 */
495 View Code Duplication
	private function generateUnknownSharesLinks(
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...
496
		DeprecatedCircle $circle, DeprecatedMember $member, string $password
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...
497
	): array {
498
		$unknownShares = $this->getUnknownShares($member);
499
500
		$data = [];
501
		foreach ($unknownShares as $share) {
502
			try {
503
				$data[] = $this->getMailLinkFromShare($share, $member, $password);
504
			} catch (TokenDoesNotExistException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
505
			}
506
		}
507
508
		return $data;
509
	}
510
511
512
	/**
513
	 * @param DeprecatedMember $member
514
	 *
515
	 * @return array
516
	 */
517 View Code Duplication
	private function getUnknownShares(DeprecatedMember $member): 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...
518
		$allShares = $this->sharesRequest->getSharesForCircle($member->getCircleId());
0 ignored issues
show
Bug introduced by
The property sharesRequest does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
519
		$knownShares = array_map(
520
			function(SharesToken $shareToken) {
521
				return $shareToken->getShareId();
522
			},
523
			$this->tokensRequest->getTokensFromMember($member)
0 ignored issues
show
Bug introduced by
The property tokensRequest does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
524
		);
525
526
		$unknownShares = [];
527
		foreach ($allShares as $share) {
528
			if (!in_array($share['id'], $knownShares)) {
529
				$unknownShares[] = $share;
530
			}
531
		}
532
533
		return $unknownShares;
534
	}
535
536
537
	/**
538
	 * @param array $share
539
	 * @param DeprecatedMember $member
540
	 * @param string $password
541
	 *
542
	 * @return array
543
	 * @throws TokenDoesNotExistException
544
	 */
545 View Code Duplication
	private function getMailLinkFromShare(array $share, DeprecatedMember $member, string $password = '') {
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...
546
		$sharesToken = $this->tokensRequest->generateTokenForMember($member, (int)$share['id'], $password);
547
		$link = $this->urlGenerator->linkToRouteAbsolute(
0 ignored issues
show
Bug introduced by
The property urlGenerator does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
548
			'files_sharing.sharecontroller.showShare',
549
			['token' => $sharesToken->getToken()]
550
		);
551
		$author = $share['uid_initiator'];
552
		$filename = basename($share['file_target']);
553
554
		return [
555
			'author'   => $author,
556
			'link'     => $link,
557
			'filename' => $filename
558
		];
559
	}
560
561
562
	/**
563
	 * @param string $author
564
	 * @param string $circleName
565
	 *
566
	 * @return IEMailTemplate
567
	 */
568 View Code Duplication
	private function generateMailExitingShares(string $author, string $circleName): IEMailTemplate {
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...
569
		$emailTemplate = $this->mailer->createEMailTemplate('circles.ExistingShareNotification', []);
0 ignored issues
show
Bug introduced by
The property mailer does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
570
		$emailTemplate->addHeader();
571
572
		$text = $this->l10n->t('%s shared multiple files with \'%s\'.', [$author, $circleName]);
0 ignored issues
show
Bug introduced by
The property l10n does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
573
		$emailTemplate->addBodyText(htmlspecialchars($text), $text);
574
575
		return $emailTemplate;
576
	}
577
578
	/**
579
	 * @param IEMailTemplate $emailTemplate
580
	 * @param array $links
581
	 */
582 View Code Duplication
	private function fillMailExistingShares(IEMailTemplate $emailTemplate, array $links) {
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...
583
		foreach ($links as $item) {
584
			$emailTemplate->addBodyButton(
585
				$this->l10n->t('Open »%s«', [htmlspecialchars($item['filename'])]), $item['link']
586
			);
587
		}
588
	}
589
590
591
	/**
592
	 * @param IEMailTemplate $emailTemplate
593
	 * @param string $author
594
	 * @param string $recipient
595
	 *
596
	 * @throws Exception
597
	 */
598 View Code Duplication
	private function sendMailExistingShares(IEMailTemplate $emailTemplate, string $author, string $recipient
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...
599
	) {
600
		$subject = $this->l10n->t('%s shared multiple files with you.', [$author]);
601
602
		$instanceName = $this->defaults->getName();
0 ignored issues
show
Bug introduced by
The property defaults does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
603
		$senderName = $this->l10n->t('%s on %s', [$author, $instanceName]);
604
605
		$message = $this->mailer->createMessage();
606
607
		$message->setFrom([Util::getDefaultEmailAddress($instanceName) => $senderName]);
608
		$message->setSubject($subject);
609
		$message->setPlainBody($emailTemplate->renderText());
610
		$message->setHtmlBody($emailTemplate->renderHtml());
611
		$message->setTo([$recipient]);
612
613
		$this->mailer->send($message);
614
	}
615
616
617
	/**
618
	 * @param string $author
619
	 * @param string $email
620
	 * @param string $password
621
	 *
622
	 * @throws Exception
623
	 */
624
	protected function sendPasswordExistingShares(string $author, string $email, string $password) {
625
		if ($password === '') {
626
			return;
627
		}
628
629
		$message = $this->mailer->createMessage();
630
631
		$authorUser = $this->userManager->get($author);
632
		$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...
633
		$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...
634
635
		$this->miscService->log("Sending password mail about existing files to '" . $email . "'", 0);
636
637
		$plainBodyPart = $this->l10n->t(
638
			"%1\$s shared multiple files with you.\nYou should have already received a separate mail with a link to access them.\n",
639
			[$authorName]
640
		);
641
		$htmlBodyPart = $this->l10n->t(
642
			'%1$s shared multiple files with you. You should have already received a separate mail with a link to access them.',
643
			[$authorName]
644
		);
645
646
		$emailTemplate = $this->mailer->createEMailTemplate(
647
			'sharebymail.RecipientPasswordNotification', [
648
														   'password' => $password,
649
														   'author'   => $author
650
													   ]
651
		);
652
653
		$emailTemplate->setSubject(
654
			$this->l10n->t(
655
				'Password to access files shared to you by %1$s', [$authorName]
656
			)
657
		);
658
		$emailTemplate->addHeader();
659
		$emailTemplate->addHeading($this->l10n->t('Password to access files'), false);
660
		$emailTemplate->addBodyText(htmlspecialchars($htmlBodyPart), $plainBodyPart);
661
		$emailTemplate->addBodyText($this->l10n->t('It is protected with the following password:'));
662
		$emailTemplate->addBodyText($password);
663
664
		// The "From" contains the sharers name
665
		$instanceName = $this->defaults->getName();
666
		$senderName = $this->l10n->t(
667
			'%1$s via %2$s',
668
			[
669
				$authorName,
670
				$instanceName
671
			]
672
		);
673
674
		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
675
		if ($authorEmail !== null) {
676
			$message->setReplyTo([$authorEmail => $authorName]);
677
			$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
678
		} else {
679
			$emailTemplate->addFooter();
680
		}
681
682
		$message->setTo([$email]);
683
		$message->useTemplate($emailTemplate);
684
		$this->mailer->send($message);
685
	}
686
687
}
688