Passed
Push — master ( 8440e5...71e26d )
by Roeland
20:39 queued 10:36
created
apps/sharebymail/lib/ShareByMailProvider.php 1 patch
Indentation   +1099 added lines, -1099 removed lines patch added patch discarded remove patch
@@ -54,1117 +54,1117 @@
 block discarded – undo
54 54
  */
55 55
 class ShareByMailProvider implements IShareProvider {
56 56
 
57
-	/** @var  IDBConnection */
58
-	private $dbConnection;
59
-
60
-	/** @var ILogger */
61
-	private $logger;
62
-
63
-	/** @var ISecureRandom */
64
-	private $secureRandom;
65
-
66
-	/** @var IUserManager */
67
-	private $userManager;
68
-
69
-	/** @var IRootFolder */
70
-	private $rootFolder;
71
-
72
-	/** @var IL10N */
73
-	private $l;
74
-
75
-	/** @var IMailer */
76
-	private $mailer;
77
-
78
-	/** @var IURLGenerator */
79
-	private $urlGenerator;
80
-
81
-	/** @var IManager  */
82
-	private $activityManager;
83
-
84
-	/** @var SettingsManager */
85
-	private $settingsManager;
86
-
87
-	/** @var Defaults */
88
-	private $defaults;
89
-
90
-	/** @var IHasher */
91
-	private $hasher;
92
-
93
-	/** @var  CapabilitiesManager */
94
-	private $capabilitiesManager;
95
-
96
-	/**
97
-	 * Return the identifier of this provider.
98
-	 *
99
-	 * @return string Containing only [a-zA-Z0-9]
100
-	 */
101
-	public function identifier() {
102
-		return 'ocMailShare';
103
-	}
104
-
105
-	/**
106
-	 * DefaultShareProvider constructor.
107
-	 *
108
-	 * @param IDBConnection $connection
109
-	 * @param ISecureRandom $secureRandom
110
-	 * @param IUserManager $userManager
111
-	 * @param IRootFolder $rootFolder
112
-	 * @param IL10N $l
113
-	 * @param ILogger $logger
114
-	 * @param IMailer $mailer
115
-	 * @param IURLGenerator $urlGenerator
116
-	 * @param IManager $activityManager
117
-	 * @param SettingsManager $settingsManager
118
-	 * @param Defaults $defaults
119
-	 * @param IHasher $hasher
120
-	 * @param CapabilitiesManager $capabilitiesManager
121
-	 */
122
-	public function __construct(
123
-		IDBConnection $connection,
124
-		ISecureRandom $secureRandom,
125
-		IUserManager $userManager,
126
-		IRootFolder $rootFolder,
127
-		IL10N $l,
128
-		ILogger $logger,
129
-		IMailer $mailer,
130
-		IURLGenerator $urlGenerator,
131
-		IManager $activityManager,
132
-		SettingsManager $settingsManager,
133
-		Defaults $defaults,
134
-		IHasher $hasher,
135
-		CapabilitiesManager $capabilitiesManager
136
-	) {
137
-		$this->dbConnection = $connection;
138
-		$this->secureRandom = $secureRandom;
139
-		$this->userManager = $userManager;
140
-		$this->rootFolder = $rootFolder;
141
-		$this->l = $l;
142
-		$this->logger = $logger;
143
-		$this->mailer = $mailer;
144
-		$this->urlGenerator = $urlGenerator;
145
-		$this->activityManager = $activityManager;
146
-		$this->settingsManager = $settingsManager;
147
-		$this->defaults = $defaults;
148
-		$this->hasher = $hasher;
149
-		$this->capabilitiesManager = $capabilitiesManager;
150
-	}
151
-
152
-	/**
153
-	 * Share a path
154
-	 *
155
-	 * @param IShare $share
156
-	 * @return IShare The share object
157
-	 * @throws ShareNotFound
158
-	 * @throws \Exception
159
-	 */
160
-	public function create(IShare $share) {
161
-
162
-		$shareWith = $share->getSharedWith();
163
-		/*
57
+    /** @var  IDBConnection */
58
+    private $dbConnection;
59
+
60
+    /** @var ILogger */
61
+    private $logger;
62
+
63
+    /** @var ISecureRandom */
64
+    private $secureRandom;
65
+
66
+    /** @var IUserManager */
67
+    private $userManager;
68
+
69
+    /** @var IRootFolder */
70
+    private $rootFolder;
71
+
72
+    /** @var IL10N */
73
+    private $l;
74
+
75
+    /** @var IMailer */
76
+    private $mailer;
77
+
78
+    /** @var IURLGenerator */
79
+    private $urlGenerator;
80
+
81
+    /** @var IManager  */
82
+    private $activityManager;
83
+
84
+    /** @var SettingsManager */
85
+    private $settingsManager;
86
+
87
+    /** @var Defaults */
88
+    private $defaults;
89
+
90
+    /** @var IHasher */
91
+    private $hasher;
92
+
93
+    /** @var  CapabilitiesManager */
94
+    private $capabilitiesManager;
95
+
96
+    /**
97
+     * Return the identifier of this provider.
98
+     *
99
+     * @return string Containing only [a-zA-Z0-9]
100
+     */
101
+    public function identifier() {
102
+        return 'ocMailShare';
103
+    }
104
+
105
+    /**
106
+     * DefaultShareProvider constructor.
107
+     *
108
+     * @param IDBConnection $connection
109
+     * @param ISecureRandom $secureRandom
110
+     * @param IUserManager $userManager
111
+     * @param IRootFolder $rootFolder
112
+     * @param IL10N $l
113
+     * @param ILogger $logger
114
+     * @param IMailer $mailer
115
+     * @param IURLGenerator $urlGenerator
116
+     * @param IManager $activityManager
117
+     * @param SettingsManager $settingsManager
118
+     * @param Defaults $defaults
119
+     * @param IHasher $hasher
120
+     * @param CapabilitiesManager $capabilitiesManager
121
+     */
122
+    public function __construct(
123
+        IDBConnection $connection,
124
+        ISecureRandom $secureRandom,
125
+        IUserManager $userManager,
126
+        IRootFolder $rootFolder,
127
+        IL10N $l,
128
+        ILogger $logger,
129
+        IMailer $mailer,
130
+        IURLGenerator $urlGenerator,
131
+        IManager $activityManager,
132
+        SettingsManager $settingsManager,
133
+        Defaults $defaults,
134
+        IHasher $hasher,
135
+        CapabilitiesManager $capabilitiesManager
136
+    ) {
137
+        $this->dbConnection = $connection;
138
+        $this->secureRandom = $secureRandom;
139
+        $this->userManager = $userManager;
140
+        $this->rootFolder = $rootFolder;
141
+        $this->l = $l;
142
+        $this->logger = $logger;
143
+        $this->mailer = $mailer;
144
+        $this->urlGenerator = $urlGenerator;
145
+        $this->activityManager = $activityManager;
146
+        $this->settingsManager = $settingsManager;
147
+        $this->defaults = $defaults;
148
+        $this->hasher = $hasher;
149
+        $this->capabilitiesManager = $capabilitiesManager;
150
+    }
151
+
152
+    /**
153
+     * Share a path
154
+     *
155
+     * @param IShare $share
156
+     * @return IShare The share object
157
+     * @throws ShareNotFound
158
+     * @throws \Exception
159
+     */
160
+    public function create(IShare $share) {
161
+
162
+        $shareWith = $share->getSharedWith();
163
+        /*
164 164
 		 * Check if file is not already shared with the remote user
165 165
 		 */
166
-		$alreadyShared = $this->getSharedWith($shareWith, \OCP\Share::SHARE_TYPE_EMAIL, $share->getNode(), 1, 0);
167
-		if (!empty($alreadyShared)) {
168
-			$message = 'Sharing %1$s failed, this item is already shared with %2$s';
169
-			$message_t = $this->l->t('Sharing %1$s failed, this item is already shared with %2$s', array($share->getNode()->getName(), $shareWith));
170
-			$this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
171
-			throw new \Exception($message_t);
172
-		}
173
-
174
-		// if the admin enforces a password for all mail shares we create a
175
-		// random password and send it to the recipient
176
-		$password = '';
177
-		$passwordEnforced = $this->settingsManager->enforcePasswordProtection();
178
-		if ($passwordEnforced) {
179
-			$password = $this->autoGeneratePassword($share);
180
-		}
181
-
182
-		$shareId = $this->createMailShare($share);
183
-		$send = $this->sendPassword($share, $password);
184
-		if ($passwordEnforced && $send === false) {
185
-			$this->sendPasswordToOwner($share, $password);
186
-		}
187
-
188
-		$this->createShareActivity($share);
189
-		$data = $this->getRawShare($shareId);
190
-
191
-		return $this->createShareObject($data);
192
-
193
-	}
194
-
195
-	/**
196
-	 * auto generate password in case of password enforcement on mail shares
197
-	 *
198
-	 * @param IShare $share
199
-	 * @return string
200
-	 * @throws \Exception
201
-	 */
202
-	protected function autoGeneratePassword($share) {
203
-		$initiatorUser = $this->userManager->get($share->getSharedBy());
204
-		$initiatorEMailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
205
-		$allowPasswordByMail = $this->settingsManager->sendPasswordByMail();
206
-
207
-		if ($initiatorEMailAddress === null && !$allowPasswordByMail) {
208
-			throw new \Exception(
209
-				$this->l->t("We can't send you the auto-generated password. Please set a valid email address in your personal settings and try again.")
210
-			);
211
-		}
212
-
213
-		$passwordPolicy = $this->getPasswordPolicy();
214
-		$passwordCharset = ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS;
215
-		$passwordLength = 8;
216
-		if (!empty($passwordPolicy)) {
217
-			$passwordLength = (int)$passwordPolicy['minLength'] > 0 ? (int)$passwordPolicy['minLength'] : $passwordLength;
218
-			$passwordCharset .= $passwordPolicy['enforceSpecialCharacters'] ? ISecureRandom::CHAR_SYMBOLS : '';
219
-		}
220
-
221
-		$password = $this->secureRandom->generate($passwordLength, $passwordCharset);
222
-
223
-		$share->setPassword($this->hasher->hash($password));
224
-
225
-		return $password;
226
-	}
227
-
228
-	/**
229
-	 * get password policy
230
-	 *
231
-	 * @return array
232
-	 */
233
-	protected function getPasswordPolicy() {
234
-		$capabilities = $this->capabilitiesManager->getCapabilities();
235
-		if (isset($capabilities['password_policy'])) {
236
-			return $capabilities['password_policy'];
237
-		}
238
-
239
-		return [];
240
-	}
241
-
242
-	/**
243
-	 * create activity if a file/folder was shared by mail
244
-	 *
245
-	 * @param IShare $share
246
-	 * @param string $type
247
-	 */
248
-	protected function createShareActivity(IShare $share, string $type = 'share') {
249
-
250
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
251
-
252
-		$this->publishActivity(
253
-			$type === 'share' ? Activity::SUBJECT_SHARED_EMAIL_SELF : Activity::SUBJECT_UNSHARED_EMAIL_SELF,
254
-			[$userFolder->getRelativePath($share->getNode()->getPath()), $share->getSharedWith()],
255
-			$share->getSharedBy(),
256
-			$share->getNode()->getId(),
257
-			$userFolder->getRelativePath($share->getNode()->getPath())
258
-		);
259
-
260
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
261
-			$ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
262
-			$fileId = $share->getNode()->getId();
263
-			$nodes = $ownerFolder->getById($fileId);
264
-			$ownerPath = $nodes[0]->getPath();
265
-			$this->publishActivity(
266
-				$type === 'share' ? Activity::SUBJECT_SHARED_EMAIL_BY : Activity::SUBJECT_UNSHARED_EMAIL_BY,
267
-				Activity::SUBJECT_SHARED_EMAIL_BY,
268
-				[$ownerFolder->getRelativePath($ownerPath), $share->getSharedWith(), $share->getSharedBy()],
269
-				$share->getShareOwner(),
270
-				$fileId,
271
-				$ownerFolder->getRelativePath($ownerPath)
272
-			);
273
-		}
274
-
275
-	}
276
-
277
-	/**
278
-	 * create activity if a file/folder was shared by mail
279
-	 *
280
-	 * @param IShare $share
281
-	 * @param string $sharedWith
282
-	 * @param bool $sendToSelf
283
-	 */
284
-	protected function createPasswordSendActivity(IShare $share, $sharedWith, $sendToSelf) {
285
-
286
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
287
-
288
-		if ($sendToSelf) {
289
-			$this->publishActivity(
290
-				Activity::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF,
291
-				[$userFolder->getRelativePath($share->getNode()->getPath())],
292
-				$share->getSharedBy(),
293
-				$share->getNode()->getId(),
294
-				$userFolder->getRelativePath($share->getNode()->getPath())
295
-			);
296
-		} else {
297
-			$this->publishActivity(
298
-				Activity::SUBJECT_SHARED_EMAIL_PASSWORD_SEND,
299
-				[$userFolder->getRelativePath($share->getNode()->getPath()), $sharedWith],
300
-				$share->getSharedBy(),
301
-				$share->getNode()->getId(),
302
-				$userFolder->getRelativePath($share->getNode()->getPath())
303
-			);
304
-		}
305
-	}
306
-
307
-
308
-	/**
309
-	 * publish activity if a file/folder was shared by mail
310
-	 *
311
-	 * @param $subject
312
-	 * @param $parameters
313
-	 * @param $affectedUser
314
-	 * @param $fileId
315
-	 * @param $filePath
316
-	 */
317
-	protected function publishActivity($subject, $parameters, $affectedUser, $fileId, $filePath) {
318
-		$event = $this->activityManager->generateEvent();
319
-		$event->setApp('sharebymail')
320
-			->setType('shared')
321
-			->setSubject($subject, $parameters)
322
-			->setAffectedUser($affectedUser)
323
-			->setObject('files', $fileId, $filePath);
324
-		$this->activityManager->publish($event);
325
-
326
-	}
327
-
328
-	/**
329
-	 * @param IShare $share
330
-	 * @return int
331
-	 * @throws \Exception
332
-	 */
333
-	protected function createMailShare(IShare $share) {
334
-		$share->setToken($this->generateToken());
335
-		$shareId = $this->addShareToDB(
336
-			$share->getNodeId(),
337
-			$share->getNodeType(),
338
-			$share->getSharedWith(),
339
-			$share->getSharedBy(),
340
-			$share->getShareOwner(),
341
-			$share->getPermissions(),
342
-			$share->getToken(),
343
-			$share->getPassword(),
344
-			$share->getSendPasswordByTalk()
345
-		);
346
-
347
-		try {
348
-			$link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
349
-				['token' => $share->getToken()]);
350
-			$this->sendMailNotification(
351
-				$share->getNode()->getName(),
352
-				$link,
353
-				$share->getSharedBy(),
354
-				$share->getSharedWith(),
355
-				$share->getExpirationDate()
356
-			);
357
-		} catch (HintException $hintException) {
358
-			$this->logger->logException($hintException, [
359
-				'message' => 'Failed to send share by mail.',
360
-				'level' => ILogger::ERROR,
361
-				'app' => 'sharebymail',
362
-			]);
363
-			$this->removeShareFromTable($shareId);
364
-			throw $hintException;
365
-		} catch (\Exception $e) {
366
-			$this->logger->logException($e, [
367
-				'message' => 'Failed to send share by mail.',
368
-				'level' => ILogger::ERROR,
369
-				'app' => 'sharebymail',
370
-			]);
371
-			$this->removeShareFromTable($shareId);
372
-			throw new HintException('Failed to send share by mail',
373
-				$this->l->t('Failed to send share by email'));
374
-		}
375
-
376
-		return $shareId;
377
-
378
-	}
379
-
380
-	/**
381
-	 * @param string $filename
382
-	 * @param string $link
383
-	 * @param string $initiator
384
-	 * @param string $shareWith
385
-	 * @param \DateTime|null $expiration
386
-	 * @throws \Exception If mail couldn't be sent
387
-	 */
388
-	protected function sendMailNotification($filename,
389
-											$link,
390
-											$initiator,
391
-											$shareWith,
392
-											\DateTime $expiration = null) {
393
-		$initiatorUser = $this->userManager->get($initiator);
394
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
395
-		$message = $this->mailer->createMessage();
396
-
397
-		$emailTemplate = $this->mailer->createEMailTemplate('sharebymail.RecipientNotification', [
398
-			'filename' => $filename,
399
-			'link' => $link,
400
-			'initiator' => $initiatorDisplayName,
401
-			'expiration' => $expiration,
402
-			'shareWith' => $shareWith,
403
-		]);
404
-
405
-		$emailTemplate->setSubject($this->l->t('%1$s shared »%2$s« with you', array($initiatorDisplayName, $filename)));
406
-		$emailTemplate->addHeader();
407
-		$emailTemplate->addHeading($this->l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false);
408
-		$text = $this->l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
409
-
410
-		$emailTemplate->addBodyText(
411
-			htmlspecialchars($text . ' ' . $this->l->t('Click the button below to open it.')),
412
-			$text
413
-		);
414
-		$emailTemplate->addBodyButton(
415
-			$this->l->t('Open »%s«', [$filename]),
416
-			$link
417
-		);
418
-
419
-		$message->setTo([$shareWith]);
420
-
421
-		// The "From" contains the sharers name
422
-		$instanceName = $this->defaults->getName();
423
-		$senderName = $this->l->t(
424
-			'%1$s via %2$s',
425
-			[
426
-				$initiatorDisplayName,
427
-				$instanceName
428
-			]
429
-		);
430
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
431
-
432
-		// The "Reply-To" is set to the sharer if an mail address is configured
433
-		// also the default footer contains a "Do not reply" which needs to be adjusted.
434
-		$initiatorEmail = $initiatorUser->getEMailAddress();
435
-		if($initiatorEmail !== null) {
436
-			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
437
-			$emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
438
-		} else {
439
-			$emailTemplate->addFooter();
440
-		}
441
-
442
-		$message->useTemplate($emailTemplate);
443
-		$this->mailer->send($message);
444
-	}
445
-
446
-	/**
447
-	 * send password to recipient of a mail share
448
-	 *
449
-	 * @param IShare $share
450
-	 * @param string $password
451
-	 * @return bool
452
-	 */
453
-	protected function sendPassword(IShare $share, $password) {
454
-
455
-		$filename = $share->getNode()->getName();
456
-		$initiator = $share->getSharedBy();
457
-		$shareWith = $share->getSharedWith();
458
-
459
-		if ($password === '' || $this->settingsManager->sendPasswordByMail() === false || $share->getSendPasswordByTalk()) {
460
-			return false;
461
-		}
462
-
463
-		$initiatorUser = $this->userManager->get($initiator);
464
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
465
-		$initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
466
-
467
-		$plainBodyPart = $this->l->t("%1\$s shared »%2\$s« with you.\nYou should have already received a separate mail with a link to access it.\n", [$initiatorDisplayName, $filename]);
468
-		$htmlBodyPart = $this->l->t('%1$s shared »%2$s« with you. You should have already received a separate mail with a link to access it.', [$initiatorDisplayName, $filename]);
469
-
470
-		$message = $this->mailer->createMessage();
471
-
472
-		$emailTemplate = $this->mailer->createEMailTemplate('sharebymail.RecipientPasswordNotification', [
473
-			'filename' => $filename,
474
-			'password' => $password,
475
-			'initiator' => $initiatorDisplayName,
476
-			'initiatorEmail' => $initiatorEmailAddress,
477
-			'shareWith' => $shareWith,
478
-		]);
479
-
480
-		$emailTemplate->setSubject($this->l->t('Password to access »%1$s« shared to you by %2$s', [$filename, $initiatorDisplayName]));
481
-		$emailTemplate->addHeader();
482
-		$emailTemplate->addHeading($this->l->t('Password to access »%s«', [$filename]), false);
483
-		$emailTemplate->addBodyText(htmlspecialchars($htmlBodyPart), $plainBodyPart);
484
-		$emailTemplate->addBodyText($this->l->t('It is protected with the following password:'));
485
-		$emailTemplate->addBodyText($password);
486
-
487
-		// The "From" contains the sharers name
488
-		$instanceName = $this->defaults->getName();
489
-		$senderName = $this->l->t(
490
-			'%1$s via %2$s',
491
-			[
492
-				$initiatorDisplayName,
493
-				$instanceName
494
-			]
495
-		);
496
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
497
-		if ($initiatorEmailAddress !== null) {
498
-			$message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
499
-			$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
500
-		} else {
501
-			$emailTemplate->addFooter();
502
-		}
503
-
504
-		$message->setTo([$shareWith]);
505
-		$message->useTemplate($emailTemplate);
506
-		$this->mailer->send($message);
507
-
508
-		$this->createPasswordSendActivity($share, $shareWith, false);
509
-
510
-		return true;
511
-	}
512
-
513
-	protected function sendNote(IShare $share) {
514
-
515
-		$recipient = $share->getSharedWith();
516
-
517
-
518
-		$filename = $share->getNode()->getName();
519
-		$initiator = $share->getSharedBy();
520
-		$note = $share->getNote();
521
-
522
-		$initiatorUser = $this->userManager->get($initiator);
523
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
524
-		$initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
525
-
526
-		$plainHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add:', [$initiatorDisplayName, $filename]);
527
-		$htmlHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add', [$initiatorDisplayName, $filename]);
528
-
529
-		$message = $this->mailer->createMessage();
530
-
531
-		$emailTemplate = $this->mailer->createEMailTemplate('shareByMail.sendNote');
532
-
533
-		$emailTemplate->setSubject($this->l->t('»%s« added a note to a file shared with you', [$initiatorDisplayName]));
534
-		$emailTemplate->addHeader();
535
-		$emailTemplate->addHeading(htmlspecialchars($htmlHeading), $plainHeading);
536
-		$emailTemplate->addBodyText(htmlspecialchars($note), $note);
537
-
538
-		$link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
539
-			['token' => $share->getToken()]);
540
-		$emailTemplate->addBodyButton(
541
-			$this->l->t('Open »%s«', [$filename]),
542
-			$link
543
-		);
544
-
545
-		// The "From" contains the sharers name
546
-		$instanceName = $this->defaults->getName();
547
-		$senderName = $this->l->t(
548
-			'%1$s via %2$s',
549
-			[
550
-				$initiatorDisplayName,
551
-				$instanceName
552
-			]
553
-		);
554
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
555
-		if ($initiatorEmailAddress !== null) {
556
-			$message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
557
-			$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
558
-		} else {
559
-			$emailTemplate->addFooter();
560
-		}
561
-
562
-		$message->setTo([$recipient]);
563
-		$message->useTemplate($emailTemplate);
564
-		$this->mailer->send($message);
565
-
566
-	}
567
-
568
-	/**
569
-	 * send auto generated password to the owner. This happens if the admin enforces
570
-	 * a password for mail shares and forbid to send the password by mail to the recipient
571
-	 *
572
-	 * @param IShare $share
573
-	 * @param string $password
574
-	 * @return bool
575
-	 * @throws \Exception
576
-	 */
577
-	protected function sendPasswordToOwner(IShare $share, $password) {
578
-
579
-		$filename = $share->getNode()->getName();
580
-		$initiator = $this->userManager->get($share->getSharedBy());
581
-		$initiatorEMailAddress = ($initiator instanceof IUser) ? $initiator->getEMailAddress() : null;
582
-		$initiatorDisplayName = ($initiator instanceof IUser) ? $initiator->getDisplayName() : $share->getSharedBy();
583
-		$shareWith = $share->getSharedWith();
584
-
585
-		if ($initiatorEMailAddress === null) {
586
-			throw new \Exception(
587
-				$this->l->t("We can't send you the auto-generated password. Please set a valid email address in your personal settings and try again.")
588
-			);
589
-		}
590
-
591
-		$bodyPart = $this->l->t('You just shared »%1$s« with %2$s. The share was already send to the recipient. Due to the security policies defined by the administrator of %3$s each share needs to be protected by password and it is not allowed to send the password directly to the recipient. Therefore you need to forward the password manually to the recipient.', [$filename, $shareWith, $this->defaults->getName()]);
592
-
593
-		$message = $this->mailer->createMessage();
594
-		$emailTemplate = $this->mailer->createEMailTemplate('sharebymail.OwnerPasswordNotification', [
595
-			'filename' => $filename,
596
-			'password' => $password,
597
-			'initiator' => $initiatorDisplayName,
598
-			'initiatorEmail' => $initiatorEMailAddress,
599
-			'shareWith' => $shareWith,
600
-		]);
601
-
602
-		$emailTemplate->setSubject($this->l->t('Password to access »%1$s« shared by you with %2$s', [$filename, $shareWith]));
603
-		$emailTemplate->addHeader();
604
-		$emailTemplate->addHeading($this->l->t('Password to access »%s«', [$filename]), false);
605
-		$emailTemplate->addBodyText($bodyPart);
606
-		$emailTemplate->addBodyText($this->l->t('This is the password:'));
607
-		$emailTemplate->addBodyText($password);
608
-		$emailTemplate->addBodyText($this->l->t('You can choose a different password at any time in the share dialog.'));
609
-		$emailTemplate->addFooter();
610
-
611
-		if ($initiatorEMailAddress) {
612
-			$message->setFrom([$initiatorEMailAddress => $initiatorDisplayName]);
613
-		}
614
-		$message->setTo([$initiatorEMailAddress => $initiatorDisplayName]);
615
-		$message->useTemplate($emailTemplate);
616
-		$this->mailer->send($message);
617
-
618
-		$this->createPasswordSendActivity($share, $shareWith, true);
619
-
620
-		return true;
621
-	}
622
-
623
-	/**
624
-	 * generate share token
625
-	 *
626
-	 * @return string
627
-	 */
628
-	protected function generateToken($size = 15) {
629
-		$token = $this->secureRandom->generate($size, ISecureRandom::CHAR_HUMAN_READABLE);
630
-		return $token;
631
-	}
632
-
633
-	/**
634
-	 * Get all children of this share
635
-	 *
636
-	 * @param IShare $parent
637
-	 * @return IShare[]
638
-	 */
639
-	public function getChildren(IShare $parent) {
640
-		$children = [];
641
-
642
-		$qb = $this->dbConnection->getQueryBuilder();
643
-		$qb->select('*')
644
-			->from('share')
645
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
646
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
647
-			->orderBy('id');
648
-
649
-		$cursor = $qb->execute();
650
-		while($data = $cursor->fetch()) {
651
-			$children[] = $this->createShareObject($data);
652
-		}
653
-		$cursor->closeCursor();
654
-
655
-		return $children;
656
-	}
657
-
658
-	/**
659
-	 * add share to the database and return the ID
660
-	 *
661
-	 * @param int $itemSource
662
-	 * @param string $itemType
663
-	 * @param string $shareWith
664
-	 * @param string $sharedBy
665
-	 * @param string $uidOwner
666
-	 * @param int $permissions
667
-	 * @param string $token
668
-	 * @param string $password
669
-	 * @param bool $sendPasswordByTalk
670
-	 * @return int
671
-	 */
672
-	protected function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token, $password, $sendPasswordByTalk) {
673
-		$qb = $this->dbConnection->getQueryBuilder();
674
-		$qb->insert('share')
675
-			->setValue('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
676
-			->setValue('item_type', $qb->createNamedParameter($itemType))
677
-			->setValue('item_source', $qb->createNamedParameter($itemSource))
678
-			->setValue('file_source', $qb->createNamedParameter($itemSource))
679
-			->setValue('share_with', $qb->createNamedParameter($shareWith))
680
-			->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
681
-			->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
682
-			->setValue('permissions', $qb->createNamedParameter($permissions))
683
-			->setValue('token', $qb->createNamedParameter($token))
684
-			->setValue('password', $qb->createNamedParameter($password))
685
-			->setValue('password_by_talk', $qb->createNamedParameter($sendPasswordByTalk, IQueryBuilder::PARAM_BOOL))
686
-			->setValue('stime', $qb->createNamedParameter(time()));
687
-
688
-		/*
166
+        $alreadyShared = $this->getSharedWith($shareWith, \OCP\Share::SHARE_TYPE_EMAIL, $share->getNode(), 1, 0);
167
+        if (!empty($alreadyShared)) {
168
+            $message = 'Sharing %1$s failed, this item is already shared with %2$s';
169
+            $message_t = $this->l->t('Sharing %1$s failed, this item is already shared with %2$s', array($share->getNode()->getName(), $shareWith));
170
+            $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
171
+            throw new \Exception($message_t);
172
+        }
173
+
174
+        // if the admin enforces a password for all mail shares we create a
175
+        // random password and send it to the recipient
176
+        $password = '';
177
+        $passwordEnforced = $this->settingsManager->enforcePasswordProtection();
178
+        if ($passwordEnforced) {
179
+            $password = $this->autoGeneratePassword($share);
180
+        }
181
+
182
+        $shareId = $this->createMailShare($share);
183
+        $send = $this->sendPassword($share, $password);
184
+        if ($passwordEnforced && $send === false) {
185
+            $this->sendPasswordToOwner($share, $password);
186
+        }
187
+
188
+        $this->createShareActivity($share);
189
+        $data = $this->getRawShare($shareId);
190
+
191
+        return $this->createShareObject($data);
192
+
193
+    }
194
+
195
+    /**
196
+     * auto generate password in case of password enforcement on mail shares
197
+     *
198
+     * @param IShare $share
199
+     * @return string
200
+     * @throws \Exception
201
+     */
202
+    protected function autoGeneratePassword($share) {
203
+        $initiatorUser = $this->userManager->get($share->getSharedBy());
204
+        $initiatorEMailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
205
+        $allowPasswordByMail = $this->settingsManager->sendPasswordByMail();
206
+
207
+        if ($initiatorEMailAddress === null && !$allowPasswordByMail) {
208
+            throw new \Exception(
209
+                $this->l->t("We can't send you the auto-generated password. Please set a valid email address in your personal settings and try again.")
210
+            );
211
+        }
212
+
213
+        $passwordPolicy = $this->getPasswordPolicy();
214
+        $passwordCharset = ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS;
215
+        $passwordLength = 8;
216
+        if (!empty($passwordPolicy)) {
217
+            $passwordLength = (int)$passwordPolicy['minLength'] > 0 ? (int)$passwordPolicy['minLength'] : $passwordLength;
218
+            $passwordCharset .= $passwordPolicy['enforceSpecialCharacters'] ? ISecureRandom::CHAR_SYMBOLS : '';
219
+        }
220
+
221
+        $password = $this->secureRandom->generate($passwordLength, $passwordCharset);
222
+
223
+        $share->setPassword($this->hasher->hash($password));
224
+
225
+        return $password;
226
+    }
227
+
228
+    /**
229
+     * get password policy
230
+     *
231
+     * @return array
232
+     */
233
+    protected function getPasswordPolicy() {
234
+        $capabilities = $this->capabilitiesManager->getCapabilities();
235
+        if (isset($capabilities['password_policy'])) {
236
+            return $capabilities['password_policy'];
237
+        }
238
+
239
+        return [];
240
+    }
241
+
242
+    /**
243
+     * create activity if a file/folder was shared by mail
244
+     *
245
+     * @param IShare $share
246
+     * @param string $type
247
+     */
248
+    protected function createShareActivity(IShare $share, string $type = 'share') {
249
+
250
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
251
+
252
+        $this->publishActivity(
253
+            $type === 'share' ? Activity::SUBJECT_SHARED_EMAIL_SELF : Activity::SUBJECT_UNSHARED_EMAIL_SELF,
254
+            [$userFolder->getRelativePath($share->getNode()->getPath()), $share->getSharedWith()],
255
+            $share->getSharedBy(),
256
+            $share->getNode()->getId(),
257
+            $userFolder->getRelativePath($share->getNode()->getPath())
258
+        );
259
+
260
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
261
+            $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
262
+            $fileId = $share->getNode()->getId();
263
+            $nodes = $ownerFolder->getById($fileId);
264
+            $ownerPath = $nodes[0]->getPath();
265
+            $this->publishActivity(
266
+                $type === 'share' ? Activity::SUBJECT_SHARED_EMAIL_BY : Activity::SUBJECT_UNSHARED_EMAIL_BY,
267
+                Activity::SUBJECT_SHARED_EMAIL_BY,
268
+                [$ownerFolder->getRelativePath($ownerPath), $share->getSharedWith(), $share->getSharedBy()],
269
+                $share->getShareOwner(),
270
+                $fileId,
271
+                $ownerFolder->getRelativePath($ownerPath)
272
+            );
273
+        }
274
+
275
+    }
276
+
277
+    /**
278
+     * create activity if a file/folder was shared by mail
279
+     *
280
+     * @param IShare $share
281
+     * @param string $sharedWith
282
+     * @param bool $sendToSelf
283
+     */
284
+    protected function createPasswordSendActivity(IShare $share, $sharedWith, $sendToSelf) {
285
+
286
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
287
+
288
+        if ($sendToSelf) {
289
+            $this->publishActivity(
290
+                Activity::SUBJECT_SHARED_EMAIL_PASSWORD_SEND_SELF,
291
+                [$userFolder->getRelativePath($share->getNode()->getPath())],
292
+                $share->getSharedBy(),
293
+                $share->getNode()->getId(),
294
+                $userFolder->getRelativePath($share->getNode()->getPath())
295
+            );
296
+        } else {
297
+            $this->publishActivity(
298
+                Activity::SUBJECT_SHARED_EMAIL_PASSWORD_SEND,
299
+                [$userFolder->getRelativePath($share->getNode()->getPath()), $sharedWith],
300
+                $share->getSharedBy(),
301
+                $share->getNode()->getId(),
302
+                $userFolder->getRelativePath($share->getNode()->getPath())
303
+            );
304
+        }
305
+    }
306
+
307
+
308
+    /**
309
+     * publish activity if a file/folder was shared by mail
310
+     *
311
+     * @param $subject
312
+     * @param $parameters
313
+     * @param $affectedUser
314
+     * @param $fileId
315
+     * @param $filePath
316
+     */
317
+    protected function publishActivity($subject, $parameters, $affectedUser, $fileId, $filePath) {
318
+        $event = $this->activityManager->generateEvent();
319
+        $event->setApp('sharebymail')
320
+            ->setType('shared')
321
+            ->setSubject($subject, $parameters)
322
+            ->setAffectedUser($affectedUser)
323
+            ->setObject('files', $fileId, $filePath);
324
+        $this->activityManager->publish($event);
325
+
326
+    }
327
+
328
+    /**
329
+     * @param IShare $share
330
+     * @return int
331
+     * @throws \Exception
332
+     */
333
+    protected function createMailShare(IShare $share) {
334
+        $share->setToken($this->generateToken());
335
+        $shareId = $this->addShareToDB(
336
+            $share->getNodeId(),
337
+            $share->getNodeType(),
338
+            $share->getSharedWith(),
339
+            $share->getSharedBy(),
340
+            $share->getShareOwner(),
341
+            $share->getPermissions(),
342
+            $share->getToken(),
343
+            $share->getPassword(),
344
+            $share->getSendPasswordByTalk()
345
+        );
346
+
347
+        try {
348
+            $link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
349
+                ['token' => $share->getToken()]);
350
+            $this->sendMailNotification(
351
+                $share->getNode()->getName(),
352
+                $link,
353
+                $share->getSharedBy(),
354
+                $share->getSharedWith(),
355
+                $share->getExpirationDate()
356
+            );
357
+        } catch (HintException $hintException) {
358
+            $this->logger->logException($hintException, [
359
+                'message' => 'Failed to send share by mail.',
360
+                'level' => ILogger::ERROR,
361
+                'app' => 'sharebymail',
362
+            ]);
363
+            $this->removeShareFromTable($shareId);
364
+            throw $hintException;
365
+        } catch (\Exception $e) {
366
+            $this->logger->logException($e, [
367
+                'message' => 'Failed to send share by mail.',
368
+                'level' => ILogger::ERROR,
369
+                'app' => 'sharebymail',
370
+            ]);
371
+            $this->removeShareFromTable($shareId);
372
+            throw new HintException('Failed to send share by mail',
373
+                $this->l->t('Failed to send share by email'));
374
+        }
375
+
376
+        return $shareId;
377
+
378
+    }
379
+
380
+    /**
381
+     * @param string $filename
382
+     * @param string $link
383
+     * @param string $initiator
384
+     * @param string $shareWith
385
+     * @param \DateTime|null $expiration
386
+     * @throws \Exception If mail couldn't be sent
387
+     */
388
+    protected function sendMailNotification($filename,
389
+                                            $link,
390
+                                            $initiator,
391
+                                            $shareWith,
392
+                                            \DateTime $expiration = null) {
393
+        $initiatorUser = $this->userManager->get($initiator);
394
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
395
+        $message = $this->mailer->createMessage();
396
+
397
+        $emailTemplate = $this->mailer->createEMailTemplate('sharebymail.RecipientNotification', [
398
+            'filename' => $filename,
399
+            'link' => $link,
400
+            'initiator' => $initiatorDisplayName,
401
+            'expiration' => $expiration,
402
+            'shareWith' => $shareWith,
403
+        ]);
404
+
405
+        $emailTemplate->setSubject($this->l->t('%1$s shared »%2$s« with you', array($initiatorDisplayName, $filename)));
406
+        $emailTemplate->addHeader();
407
+        $emailTemplate->addHeading($this->l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false);
408
+        $text = $this->l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
409
+
410
+        $emailTemplate->addBodyText(
411
+            htmlspecialchars($text . ' ' . $this->l->t('Click the button below to open it.')),
412
+            $text
413
+        );
414
+        $emailTemplate->addBodyButton(
415
+            $this->l->t('Open »%s«', [$filename]),
416
+            $link
417
+        );
418
+
419
+        $message->setTo([$shareWith]);
420
+
421
+        // The "From" contains the sharers name
422
+        $instanceName = $this->defaults->getName();
423
+        $senderName = $this->l->t(
424
+            '%1$s via %2$s',
425
+            [
426
+                $initiatorDisplayName,
427
+                $instanceName
428
+            ]
429
+        );
430
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
431
+
432
+        // The "Reply-To" is set to the sharer if an mail address is configured
433
+        // also the default footer contains a "Do not reply" which needs to be adjusted.
434
+        $initiatorEmail = $initiatorUser->getEMailAddress();
435
+        if($initiatorEmail !== null) {
436
+            $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
437
+            $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
438
+        } else {
439
+            $emailTemplate->addFooter();
440
+        }
441
+
442
+        $message->useTemplate($emailTemplate);
443
+        $this->mailer->send($message);
444
+    }
445
+
446
+    /**
447
+     * send password to recipient of a mail share
448
+     *
449
+     * @param IShare $share
450
+     * @param string $password
451
+     * @return bool
452
+     */
453
+    protected function sendPassword(IShare $share, $password) {
454
+
455
+        $filename = $share->getNode()->getName();
456
+        $initiator = $share->getSharedBy();
457
+        $shareWith = $share->getSharedWith();
458
+
459
+        if ($password === '' || $this->settingsManager->sendPasswordByMail() === false || $share->getSendPasswordByTalk()) {
460
+            return false;
461
+        }
462
+
463
+        $initiatorUser = $this->userManager->get($initiator);
464
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
465
+        $initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
466
+
467
+        $plainBodyPart = $this->l->t("%1\$s shared »%2\$s« with you.\nYou should have already received a separate mail with a link to access it.\n", [$initiatorDisplayName, $filename]);
468
+        $htmlBodyPart = $this->l->t('%1$s shared »%2$s« with you. You should have already received a separate mail with a link to access it.', [$initiatorDisplayName, $filename]);
469
+
470
+        $message = $this->mailer->createMessage();
471
+
472
+        $emailTemplate = $this->mailer->createEMailTemplate('sharebymail.RecipientPasswordNotification', [
473
+            'filename' => $filename,
474
+            'password' => $password,
475
+            'initiator' => $initiatorDisplayName,
476
+            'initiatorEmail' => $initiatorEmailAddress,
477
+            'shareWith' => $shareWith,
478
+        ]);
479
+
480
+        $emailTemplate->setSubject($this->l->t('Password to access »%1$s« shared to you by %2$s', [$filename, $initiatorDisplayName]));
481
+        $emailTemplate->addHeader();
482
+        $emailTemplate->addHeading($this->l->t('Password to access »%s«', [$filename]), false);
483
+        $emailTemplate->addBodyText(htmlspecialchars($htmlBodyPart), $plainBodyPart);
484
+        $emailTemplate->addBodyText($this->l->t('It is protected with the following password:'));
485
+        $emailTemplate->addBodyText($password);
486
+
487
+        // The "From" contains the sharers name
488
+        $instanceName = $this->defaults->getName();
489
+        $senderName = $this->l->t(
490
+            '%1$s via %2$s',
491
+            [
492
+                $initiatorDisplayName,
493
+                $instanceName
494
+            ]
495
+        );
496
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
497
+        if ($initiatorEmailAddress !== null) {
498
+            $message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
499
+            $emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
500
+        } else {
501
+            $emailTemplate->addFooter();
502
+        }
503
+
504
+        $message->setTo([$shareWith]);
505
+        $message->useTemplate($emailTemplate);
506
+        $this->mailer->send($message);
507
+
508
+        $this->createPasswordSendActivity($share, $shareWith, false);
509
+
510
+        return true;
511
+    }
512
+
513
+    protected function sendNote(IShare $share) {
514
+
515
+        $recipient = $share->getSharedWith();
516
+
517
+
518
+        $filename = $share->getNode()->getName();
519
+        $initiator = $share->getSharedBy();
520
+        $note = $share->getNote();
521
+
522
+        $initiatorUser = $this->userManager->get($initiator);
523
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
524
+        $initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
525
+
526
+        $plainHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add:', [$initiatorDisplayName, $filename]);
527
+        $htmlHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add', [$initiatorDisplayName, $filename]);
528
+
529
+        $message = $this->mailer->createMessage();
530
+
531
+        $emailTemplate = $this->mailer->createEMailTemplate('shareByMail.sendNote');
532
+
533
+        $emailTemplate->setSubject($this->l->t('»%s« added a note to a file shared with you', [$initiatorDisplayName]));
534
+        $emailTemplate->addHeader();
535
+        $emailTemplate->addHeading(htmlspecialchars($htmlHeading), $plainHeading);
536
+        $emailTemplate->addBodyText(htmlspecialchars($note), $note);
537
+
538
+        $link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
539
+            ['token' => $share->getToken()]);
540
+        $emailTemplate->addBodyButton(
541
+            $this->l->t('Open »%s«', [$filename]),
542
+            $link
543
+        );
544
+
545
+        // The "From" contains the sharers name
546
+        $instanceName = $this->defaults->getName();
547
+        $senderName = $this->l->t(
548
+            '%1$s via %2$s',
549
+            [
550
+                $initiatorDisplayName,
551
+                $instanceName
552
+            ]
553
+        );
554
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
555
+        if ($initiatorEmailAddress !== null) {
556
+            $message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
557
+            $emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
558
+        } else {
559
+            $emailTemplate->addFooter();
560
+        }
561
+
562
+        $message->setTo([$recipient]);
563
+        $message->useTemplate($emailTemplate);
564
+        $this->mailer->send($message);
565
+
566
+    }
567
+
568
+    /**
569
+     * send auto generated password to the owner. This happens if the admin enforces
570
+     * a password for mail shares and forbid to send the password by mail to the recipient
571
+     *
572
+     * @param IShare $share
573
+     * @param string $password
574
+     * @return bool
575
+     * @throws \Exception
576
+     */
577
+    protected function sendPasswordToOwner(IShare $share, $password) {
578
+
579
+        $filename = $share->getNode()->getName();
580
+        $initiator = $this->userManager->get($share->getSharedBy());
581
+        $initiatorEMailAddress = ($initiator instanceof IUser) ? $initiator->getEMailAddress() : null;
582
+        $initiatorDisplayName = ($initiator instanceof IUser) ? $initiator->getDisplayName() : $share->getSharedBy();
583
+        $shareWith = $share->getSharedWith();
584
+
585
+        if ($initiatorEMailAddress === null) {
586
+            throw new \Exception(
587
+                $this->l->t("We can't send you the auto-generated password. Please set a valid email address in your personal settings and try again.")
588
+            );
589
+        }
590
+
591
+        $bodyPart = $this->l->t('You just shared »%1$s« with %2$s. The share was already send to the recipient. Due to the security policies defined by the administrator of %3$s each share needs to be protected by password and it is not allowed to send the password directly to the recipient. Therefore you need to forward the password manually to the recipient.', [$filename, $shareWith, $this->defaults->getName()]);
592
+
593
+        $message = $this->mailer->createMessage();
594
+        $emailTemplate = $this->mailer->createEMailTemplate('sharebymail.OwnerPasswordNotification', [
595
+            'filename' => $filename,
596
+            'password' => $password,
597
+            'initiator' => $initiatorDisplayName,
598
+            'initiatorEmail' => $initiatorEMailAddress,
599
+            'shareWith' => $shareWith,
600
+        ]);
601
+
602
+        $emailTemplate->setSubject($this->l->t('Password to access »%1$s« shared by you with %2$s', [$filename, $shareWith]));
603
+        $emailTemplate->addHeader();
604
+        $emailTemplate->addHeading($this->l->t('Password to access »%s«', [$filename]), false);
605
+        $emailTemplate->addBodyText($bodyPart);
606
+        $emailTemplate->addBodyText($this->l->t('This is the password:'));
607
+        $emailTemplate->addBodyText($password);
608
+        $emailTemplate->addBodyText($this->l->t('You can choose a different password at any time in the share dialog.'));
609
+        $emailTemplate->addFooter();
610
+
611
+        if ($initiatorEMailAddress) {
612
+            $message->setFrom([$initiatorEMailAddress => $initiatorDisplayName]);
613
+        }
614
+        $message->setTo([$initiatorEMailAddress => $initiatorDisplayName]);
615
+        $message->useTemplate($emailTemplate);
616
+        $this->mailer->send($message);
617
+
618
+        $this->createPasswordSendActivity($share, $shareWith, true);
619
+
620
+        return true;
621
+    }
622
+
623
+    /**
624
+     * generate share token
625
+     *
626
+     * @return string
627
+     */
628
+    protected function generateToken($size = 15) {
629
+        $token = $this->secureRandom->generate($size, ISecureRandom::CHAR_HUMAN_READABLE);
630
+        return $token;
631
+    }
632
+
633
+    /**
634
+     * Get all children of this share
635
+     *
636
+     * @param IShare $parent
637
+     * @return IShare[]
638
+     */
639
+    public function getChildren(IShare $parent) {
640
+        $children = [];
641
+
642
+        $qb = $this->dbConnection->getQueryBuilder();
643
+        $qb->select('*')
644
+            ->from('share')
645
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
646
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
647
+            ->orderBy('id');
648
+
649
+        $cursor = $qb->execute();
650
+        while($data = $cursor->fetch()) {
651
+            $children[] = $this->createShareObject($data);
652
+        }
653
+        $cursor->closeCursor();
654
+
655
+        return $children;
656
+    }
657
+
658
+    /**
659
+     * add share to the database and return the ID
660
+     *
661
+     * @param int $itemSource
662
+     * @param string $itemType
663
+     * @param string $shareWith
664
+     * @param string $sharedBy
665
+     * @param string $uidOwner
666
+     * @param int $permissions
667
+     * @param string $token
668
+     * @param string $password
669
+     * @param bool $sendPasswordByTalk
670
+     * @return int
671
+     */
672
+    protected function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token, $password, $sendPasswordByTalk) {
673
+        $qb = $this->dbConnection->getQueryBuilder();
674
+        $qb->insert('share')
675
+            ->setValue('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
676
+            ->setValue('item_type', $qb->createNamedParameter($itemType))
677
+            ->setValue('item_source', $qb->createNamedParameter($itemSource))
678
+            ->setValue('file_source', $qb->createNamedParameter($itemSource))
679
+            ->setValue('share_with', $qb->createNamedParameter($shareWith))
680
+            ->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
681
+            ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
682
+            ->setValue('permissions', $qb->createNamedParameter($permissions))
683
+            ->setValue('token', $qb->createNamedParameter($token))
684
+            ->setValue('password', $qb->createNamedParameter($password))
685
+            ->setValue('password_by_talk', $qb->createNamedParameter($sendPasswordByTalk, IQueryBuilder::PARAM_BOOL))
686
+            ->setValue('stime', $qb->createNamedParameter(time()));
687
+
688
+        /*
689 689
 		 * Added to fix https://github.com/owncloud/core/issues/22215
690 690
 		 * Can be removed once we get rid of ajax/share.php
691 691
 		 */
692
-		$qb->setValue('file_target', $qb->createNamedParameter(''));
692
+        $qb->setValue('file_target', $qb->createNamedParameter(''));
693 693
 
694
-		$qb->execute();
695
-		$id = $qb->getLastInsertId();
694
+        $qb->execute();
695
+        $id = $qb->getLastInsertId();
696 696
 
697
-		return (int)$id;
698
-	}
697
+        return (int)$id;
698
+    }
699 699
 
700
-	/**
701
-	 * Update a share
702
-	 *
703
-	 * @param IShare $share
704
-	 * @param string|null $plainTextPassword
705
-	 * @return IShare The share object
706
-	 */
707
-	public function update(IShare $share, $plainTextPassword = null) {
700
+    /**
701
+     * Update a share
702
+     *
703
+     * @param IShare $share
704
+     * @param string|null $plainTextPassword
705
+     * @return IShare The share object
706
+     */
707
+    public function update(IShare $share, $plainTextPassword = null) {
708 708
 
709
-		$originalShare = $this->getShareById($share->getId());
709
+        $originalShare = $this->getShareById($share->getId());
710 710
 
711
-		// a real password was given
712
-		$validPassword = $plainTextPassword !== null && $plainTextPassword !== '';
711
+        // a real password was given
712
+        $validPassword = $plainTextPassword !== null && $plainTextPassword !== '';
713 713
 
714
-		if($validPassword && ($originalShare->getPassword() !== $share->getPassword() ||
715
-								($originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk()))) {
716
-			$this->sendPassword($share, $plainTextPassword);
717
-		}
718
-		/*
714
+        if($validPassword && ($originalShare->getPassword() !== $share->getPassword() ||
715
+                                ($originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk()))) {
716
+            $this->sendPassword($share, $plainTextPassword);
717
+        }
718
+        /*
719 719
 		 * We allow updating the permissions and password of mail shares
720 720
 		 */
721
-		$qb = $this->dbConnection->getQueryBuilder();
722
-		$qb->update('share')
723
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
724
-			->set('permissions', $qb->createNamedParameter($share->getPermissions()))
725
-			->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
726
-			->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
727
-			->set('password', $qb->createNamedParameter($share->getPassword()))
728
-			->set('password_by_talk', $qb->createNamedParameter($share->getSendPasswordByTalk(), IQueryBuilder::PARAM_BOOL))
729
-			->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
730
-			->set('note', $qb->createNamedParameter($share->getNote()))
731
-			->execute();
732
-
733
-		if ($originalShare->getNote() !== $share->getNote() && $share->getNote() !== '') {
734
-			$this->sendNote($share);
735
-		}
736
-
737
-		return $share;
738
-	}
739
-
740
-	/**
741
-	 * @inheritdoc
742
-	 */
743
-	public function move(IShare $share, $recipient) {
744
-		/**
745
-		 * nothing to do here, mail shares are only outgoing shares
746
-		 */
747
-		return $share;
748
-	}
749
-
750
-	/**
751
-	 * Delete a share (owner unShares the file)
752
-	 *
753
-	 * @param IShare $share
754
-	 */
755
-	public function delete(IShare $share) {
756
-		try {
757
-			$this->createShareActivity($share, 'unshare');
758
-		} catch (\Exception $e) {
759
-		}
760
-
761
-		$this->removeShareFromTable($share->getId());
762
-	}
763
-
764
-	/**
765
-	 * @inheritdoc
766
-	 */
767
-	public function deleteFromSelf(IShare $share, $recipient) {
768
-		// nothing to do here, mail shares are only outgoing shares
769
-	}
770
-
771
-	public function restore(IShare $share, string $recipient): IShare {
772
-		throw new GenericShareException('not implemented');
773
-	}
774
-
775
-	/**
776
-	 * @inheritdoc
777
-	 */
778
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
779
-		$qb = $this->dbConnection->getQueryBuilder();
780
-		$qb->select('*')
781
-			->from('share');
782
-
783
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
784
-
785
-		/**
786
-		 * Reshares for this user are shares where they are the owner.
787
-		 */
788
-		if ($reshares === false) {
789
-			//Special case for old shares created via the web UI
790
-			$or1 = $qb->expr()->andX(
791
-				$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
792
-				$qb->expr()->isNull('uid_initiator')
793
-			);
794
-
795
-			$qb->andWhere(
796
-				$qb->expr()->orX(
797
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
798
-					$or1
799
-				)
800
-			);
801
-		} else {
802
-			$qb->andWhere(
803
-				$qb->expr()->orX(
804
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
805
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
806
-				)
807
-			);
808
-		}
809
-
810
-		if ($node !== null) {
811
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
812
-		}
813
-
814
-		if ($limit !== -1) {
815
-			$qb->setMaxResults($limit);
816
-		}
817
-
818
-		$qb->setFirstResult($offset);
819
-		$qb->orderBy('id');
820
-
821
-		$cursor = $qb->execute();
822
-		$shares = [];
823
-		while($data = $cursor->fetch()) {
824
-			$shares[] = $this->createShareObject($data);
825
-		}
826
-		$cursor->closeCursor();
827
-
828
-		return $shares;
829
-	}
830
-
831
-	/**
832
-	 * @inheritdoc
833
-	 */
834
-	public function getShareById($id, $recipientId = null) {
835
-		$qb = $this->dbConnection->getQueryBuilder();
836
-
837
-		$qb->select('*')
838
-			->from('share')
839
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
840
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
841
-
842
-		$cursor = $qb->execute();
843
-		$data = $cursor->fetch();
844
-		$cursor->closeCursor();
845
-
846
-		if ($data === false) {
847
-			throw new ShareNotFound();
848
-		}
849
-
850
-		try {
851
-			$share = $this->createShareObject($data);
852
-		} catch (InvalidShare $e) {
853
-			throw new ShareNotFound();
854
-		}
855
-
856
-		return $share;
857
-	}
858
-
859
-	/**
860
-	 * Get shares for a given path
861
-	 *
862
-	 * @param \OCP\Files\Node $path
863
-	 * @return IShare[]
864
-	 */
865
-	public function getSharesByPath(Node $path) {
866
-		$qb = $this->dbConnection->getQueryBuilder();
867
-
868
-		$cursor = $qb->select('*')
869
-			->from('share')
870
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
871
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
872
-			->execute();
873
-
874
-		$shares = [];
875
-		while($data = $cursor->fetch()) {
876
-			$shares[] = $this->createShareObject($data);
877
-		}
878
-		$cursor->closeCursor();
879
-
880
-		return $shares;
881
-	}
882
-
883
-	/**
884
-	 * @inheritdoc
885
-	 */
886
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
887
-		/** @var IShare[] $shares */
888
-		$shares = [];
889
-
890
-		//Get shares directly with this user
891
-		$qb = $this->dbConnection->getQueryBuilder();
892
-		$qb->select('*')
893
-			->from('share');
894
-
895
-		// Order by id
896
-		$qb->orderBy('id');
897
-
898
-		// Set limit and offset
899
-		if ($limit !== -1) {
900
-			$qb->setMaxResults($limit);
901
-		}
902
-		$qb->setFirstResult($offset);
903
-
904
-		$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
905
-		$qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
906
-
907
-		// Filter by node if provided
908
-		if ($node !== null) {
909
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
910
-		}
911
-
912
-		$cursor = $qb->execute();
913
-
914
-		while($data = $cursor->fetch()) {
915
-			$shares[] = $this->createShareObject($data);
916
-		}
917
-		$cursor->closeCursor();
918
-
919
-
920
-		return $shares;
921
-	}
922
-
923
-	/**
924
-	 * Get a share by token
925
-	 *
926
-	 * @param string $token
927
-	 * @return IShare
928
-	 * @throws ShareNotFound
929
-	 */
930
-	public function getShareByToken($token) {
931
-		$qb = $this->dbConnection->getQueryBuilder();
932
-
933
-		$cursor = $qb->select('*')
934
-			->from('share')
935
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
936
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
937
-			->execute();
938
-
939
-		$data = $cursor->fetch();
940
-
941
-		if ($data === false) {
942
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
943
-		}
944
-
945
-		try {
946
-			$share = $this->createShareObject($data);
947
-		} catch (InvalidShare $e) {
948
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
949
-		}
950
-
951
-		return $share;
952
-	}
953
-
954
-	/**
955
-	 * remove share from table
956
-	 *
957
-	 * @param string $shareId
958
-	 */
959
-	protected function removeShareFromTable($shareId) {
960
-		$qb = $this->dbConnection->getQueryBuilder();
961
-		$qb->delete('share')
962
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
963
-		$qb->execute();
964
-	}
965
-
966
-	/**
967
-	 * Create a share object from an database row
968
-	 *
969
-	 * @param array $data
970
-	 * @return IShare
971
-	 * @throws InvalidShare
972
-	 * @throws ShareNotFound
973
-	 */
974
-	protected function createShareObject($data) {
975
-
976
-		$share = new Share($this->rootFolder, $this->userManager);
977
-		$share->setId((int)$data['id'])
978
-			->setShareType((int)$data['share_type'])
979
-			->setPermissions((int)$data['permissions'])
980
-			->setTarget($data['file_target'])
981
-			->setMailSend((bool)$data['mail_send'])
982
-			->setNote($data['note'])
983
-			->setToken($data['token']);
984
-
985
-		$shareTime = new \DateTime();
986
-		$shareTime->setTimestamp((int)$data['stime']);
987
-		$share->setShareTime($shareTime);
988
-		$share->setSharedWith($data['share_with']);
989
-		$share->setPassword($data['password']);
990
-		$share->setSendPasswordByTalk((bool)$data['password_by_talk']);
991
-
992
-		if ($data['uid_initiator'] !== null) {
993
-			$share->setShareOwner($data['uid_owner']);
994
-			$share->setSharedBy($data['uid_initiator']);
995
-		} else {
996
-			//OLD SHARE
997
-			$share->setSharedBy($data['uid_owner']);
998
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
999
-
1000
-			$owner = $path->getOwner();
1001
-			$share->setShareOwner($owner->getUID());
1002
-		}
1003
-
1004
-		if ($data['expiration'] !== null) {
1005
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
1006
-			if ($expiration !== false) {
1007
-				$share->setExpirationDate($expiration);
1008
-			}
1009
-		}
1010
-
1011
-		$share->setNodeId((int)$data['file_source']);
1012
-		$share->setNodeType($data['item_type']);
1013
-
1014
-		$share->setProviderId($this->identifier());
1015
-
1016
-		return $share;
1017
-	}
1018
-
1019
-	/**
1020
-	 * Get the node with file $id for $user
1021
-	 *
1022
-	 * @param string $userId
1023
-	 * @param int $id
1024
-	 * @return \OCP\Files\File|\OCP\Files\Folder
1025
-	 * @throws InvalidShare
1026
-	 */
1027
-	private function getNode($userId, $id) {
1028
-		try {
1029
-			$userFolder = $this->rootFolder->getUserFolder($userId);
1030
-		} catch (NoUserException $e) {
1031
-			throw new InvalidShare();
1032
-		}
1033
-
1034
-		$nodes = $userFolder->getById($id);
1035
-
1036
-		if (empty($nodes)) {
1037
-			throw new InvalidShare();
1038
-		}
1039
-
1040
-		return $nodes[0];
1041
-	}
1042
-
1043
-	/**
1044
-	 * A user is deleted from the system
1045
-	 * So clean up the relevant shares.
1046
-	 *
1047
-	 * @param string $uid
1048
-	 * @param int $shareType
1049
-	 */
1050
-	public function userDeleted($uid, $shareType) {
1051
-		$qb = $this->dbConnection->getQueryBuilder();
1052
-
1053
-		$qb->delete('share')
1054
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
1055
-			->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
1056
-			->execute();
1057
-	}
1058
-
1059
-	/**
1060
-	 * This provider does not support group shares
1061
-	 *
1062
-	 * @param string $gid
1063
-	 */
1064
-	public function groupDeleted($gid) {
1065
-	}
1066
-
1067
-	/**
1068
-	 * This provider does not support group shares
1069
-	 *
1070
-	 * @param string $uid
1071
-	 * @param string $gid
1072
-	 */
1073
-	public function userDeletedFromGroup($uid, $gid) {
1074
-	}
1075
-
1076
-	/**
1077
-	 * get database row of a give share
1078
-	 *
1079
-	 * @param $id
1080
-	 * @return array
1081
-	 * @throws ShareNotFound
1082
-	 */
1083
-	protected function getRawShare($id) {
1084
-
1085
-		// Now fetch the inserted share and create a complete share object
1086
-		$qb = $this->dbConnection->getQueryBuilder();
1087
-		$qb->select('*')
1088
-			->from('share')
1089
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
1090
-
1091
-		$cursor = $qb->execute();
1092
-		$data = $cursor->fetch();
1093
-		$cursor->closeCursor();
1094
-
1095
-		if ($data === false) {
1096
-			throw new ShareNotFound;
1097
-		}
1098
-
1099
-		return $data;
1100
-	}
1101
-
1102
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
1103
-		$qb = $this->dbConnection->getQueryBuilder();
1104
-		$qb->select('*')
1105
-			->from('share', 's')
1106
-			->andWhere($qb->expr()->orX(
1107
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1108
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1109
-			))
1110
-			->andWhere(
1111
-				$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
1112
-			);
1113
-
1114
-		/**
1115
-		 * Reshares for this user are shares where they are the owner.
1116
-		 */
1117
-		if ($reshares === false) {
1118
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
1119
-		} else {
1120
-			$qb->andWhere(
1121
-				$qb->expr()->orX(
1122
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
1123
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
1124
-				)
1125
-			);
1126
-		}
1127
-
1128
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
1129
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
1130
-
1131
-		$qb->orderBy('id');
1132
-
1133
-		$cursor = $qb->execute();
1134
-		$shares = [];
1135
-		while ($data = $cursor->fetch()) {
1136
-			$shares[$data['fileid']][] = $this->createShareObject($data);
1137
-		}
1138
-		$cursor->closeCursor();
1139
-
1140
-		return $shares;
1141
-	}
1142
-
1143
-	/**
1144
-	 * @inheritdoc
1145
-	 */
1146
-	public function getAccessList($nodes, $currentAccess) {
1147
-		$ids = [];
1148
-		foreach ($nodes as $node) {
1149
-			$ids[] = $node->getId();
1150
-		}
1151
-
1152
-		$qb = $this->dbConnection->getQueryBuilder();
1153
-		$qb->select('share_with')
1154
-			->from('share')
1155
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
1156
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1157
-			->andWhere($qb->expr()->orX(
1158
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1159
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1160
-			))
1161
-			->setMaxResults(1);
1162
-		$cursor = $qb->execute();
1163
-
1164
-		$mail = $cursor->fetch() !== false;
1165
-		$cursor->closeCursor();
1166
-
1167
-		return ['public' => $mail];
1168
-	}
721
+        $qb = $this->dbConnection->getQueryBuilder();
722
+        $qb->update('share')
723
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
724
+            ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
725
+            ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
726
+            ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
727
+            ->set('password', $qb->createNamedParameter($share->getPassword()))
728
+            ->set('password_by_talk', $qb->createNamedParameter($share->getSendPasswordByTalk(), IQueryBuilder::PARAM_BOOL))
729
+            ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
730
+            ->set('note', $qb->createNamedParameter($share->getNote()))
731
+            ->execute();
732
+
733
+        if ($originalShare->getNote() !== $share->getNote() && $share->getNote() !== '') {
734
+            $this->sendNote($share);
735
+        }
736
+
737
+        return $share;
738
+    }
739
+
740
+    /**
741
+     * @inheritdoc
742
+     */
743
+    public function move(IShare $share, $recipient) {
744
+        /**
745
+         * nothing to do here, mail shares are only outgoing shares
746
+         */
747
+        return $share;
748
+    }
749
+
750
+    /**
751
+     * Delete a share (owner unShares the file)
752
+     *
753
+     * @param IShare $share
754
+     */
755
+    public function delete(IShare $share) {
756
+        try {
757
+            $this->createShareActivity($share, 'unshare');
758
+        } catch (\Exception $e) {
759
+        }
760
+
761
+        $this->removeShareFromTable($share->getId());
762
+    }
763
+
764
+    /**
765
+     * @inheritdoc
766
+     */
767
+    public function deleteFromSelf(IShare $share, $recipient) {
768
+        // nothing to do here, mail shares are only outgoing shares
769
+    }
770
+
771
+    public function restore(IShare $share, string $recipient): IShare {
772
+        throw new GenericShareException('not implemented');
773
+    }
774
+
775
+    /**
776
+     * @inheritdoc
777
+     */
778
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
779
+        $qb = $this->dbConnection->getQueryBuilder();
780
+        $qb->select('*')
781
+            ->from('share');
782
+
783
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
784
+
785
+        /**
786
+         * Reshares for this user are shares where they are the owner.
787
+         */
788
+        if ($reshares === false) {
789
+            //Special case for old shares created via the web UI
790
+            $or1 = $qb->expr()->andX(
791
+                $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
792
+                $qb->expr()->isNull('uid_initiator')
793
+            );
794
+
795
+            $qb->andWhere(
796
+                $qb->expr()->orX(
797
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
798
+                    $or1
799
+                )
800
+            );
801
+        } else {
802
+            $qb->andWhere(
803
+                $qb->expr()->orX(
804
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
805
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
806
+                )
807
+            );
808
+        }
809
+
810
+        if ($node !== null) {
811
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
812
+        }
813
+
814
+        if ($limit !== -1) {
815
+            $qb->setMaxResults($limit);
816
+        }
817
+
818
+        $qb->setFirstResult($offset);
819
+        $qb->orderBy('id');
820
+
821
+        $cursor = $qb->execute();
822
+        $shares = [];
823
+        while($data = $cursor->fetch()) {
824
+            $shares[] = $this->createShareObject($data);
825
+        }
826
+        $cursor->closeCursor();
827
+
828
+        return $shares;
829
+    }
830
+
831
+    /**
832
+     * @inheritdoc
833
+     */
834
+    public function getShareById($id, $recipientId = null) {
835
+        $qb = $this->dbConnection->getQueryBuilder();
836
+
837
+        $qb->select('*')
838
+            ->from('share')
839
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
840
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
841
+
842
+        $cursor = $qb->execute();
843
+        $data = $cursor->fetch();
844
+        $cursor->closeCursor();
845
+
846
+        if ($data === false) {
847
+            throw new ShareNotFound();
848
+        }
849
+
850
+        try {
851
+            $share = $this->createShareObject($data);
852
+        } catch (InvalidShare $e) {
853
+            throw new ShareNotFound();
854
+        }
855
+
856
+        return $share;
857
+    }
858
+
859
+    /**
860
+     * Get shares for a given path
861
+     *
862
+     * @param \OCP\Files\Node $path
863
+     * @return IShare[]
864
+     */
865
+    public function getSharesByPath(Node $path) {
866
+        $qb = $this->dbConnection->getQueryBuilder();
867
+
868
+        $cursor = $qb->select('*')
869
+            ->from('share')
870
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
871
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
872
+            ->execute();
873
+
874
+        $shares = [];
875
+        while($data = $cursor->fetch()) {
876
+            $shares[] = $this->createShareObject($data);
877
+        }
878
+        $cursor->closeCursor();
879
+
880
+        return $shares;
881
+    }
882
+
883
+    /**
884
+     * @inheritdoc
885
+     */
886
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
887
+        /** @var IShare[] $shares */
888
+        $shares = [];
889
+
890
+        //Get shares directly with this user
891
+        $qb = $this->dbConnection->getQueryBuilder();
892
+        $qb->select('*')
893
+            ->from('share');
894
+
895
+        // Order by id
896
+        $qb->orderBy('id');
897
+
898
+        // Set limit and offset
899
+        if ($limit !== -1) {
900
+            $qb->setMaxResults($limit);
901
+        }
902
+        $qb->setFirstResult($offset);
903
+
904
+        $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
905
+        $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
906
+
907
+        // Filter by node if provided
908
+        if ($node !== null) {
909
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
910
+        }
911
+
912
+        $cursor = $qb->execute();
913
+
914
+        while($data = $cursor->fetch()) {
915
+            $shares[] = $this->createShareObject($data);
916
+        }
917
+        $cursor->closeCursor();
918
+
919
+
920
+        return $shares;
921
+    }
922
+
923
+    /**
924
+     * Get a share by token
925
+     *
926
+     * @param string $token
927
+     * @return IShare
928
+     * @throws ShareNotFound
929
+     */
930
+    public function getShareByToken($token) {
931
+        $qb = $this->dbConnection->getQueryBuilder();
932
+
933
+        $cursor = $qb->select('*')
934
+            ->from('share')
935
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
936
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
937
+            ->execute();
938
+
939
+        $data = $cursor->fetch();
940
+
941
+        if ($data === false) {
942
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
943
+        }
944
+
945
+        try {
946
+            $share = $this->createShareObject($data);
947
+        } catch (InvalidShare $e) {
948
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
949
+        }
950
+
951
+        return $share;
952
+    }
953
+
954
+    /**
955
+     * remove share from table
956
+     *
957
+     * @param string $shareId
958
+     */
959
+    protected function removeShareFromTable($shareId) {
960
+        $qb = $this->dbConnection->getQueryBuilder();
961
+        $qb->delete('share')
962
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
963
+        $qb->execute();
964
+    }
965
+
966
+    /**
967
+     * Create a share object from an database row
968
+     *
969
+     * @param array $data
970
+     * @return IShare
971
+     * @throws InvalidShare
972
+     * @throws ShareNotFound
973
+     */
974
+    protected function createShareObject($data) {
975
+
976
+        $share = new Share($this->rootFolder, $this->userManager);
977
+        $share->setId((int)$data['id'])
978
+            ->setShareType((int)$data['share_type'])
979
+            ->setPermissions((int)$data['permissions'])
980
+            ->setTarget($data['file_target'])
981
+            ->setMailSend((bool)$data['mail_send'])
982
+            ->setNote($data['note'])
983
+            ->setToken($data['token']);
984
+
985
+        $shareTime = new \DateTime();
986
+        $shareTime->setTimestamp((int)$data['stime']);
987
+        $share->setShareTime($shareTime);
988
+        $share->setSharedWith($data['share_with']);
989
+        $share->setPassword($data['password']);
990
+        $share->setSendPasswordByTalk((bool)$data['password_by_talk']);
991
+
992
+        if ($data['uid_initiator'] !== null) {
993
+            $share->setShareOwner($data['uid_owner']);
994
+            $share->setSharedBy($data['uid_initiator']);
995
+        } else {
996
+            //OLD SHARE
997
+            $share->setSharedBy($data['uid_owner']);
998
+            $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
999
+
1000
+            $owner = $path->getOwner();
1001
+            $share->setShareOwner($owner->getUID());
1002
+        }
1003
+
1004
+        if ($data['expiration'] !== null) {
1005
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
1006
+            if ($expiration !== false) {
1007
+                $share->setExpirationDate($expiration);
1008
+            }
1009
+        }
1010
+
1011
+        $share->setNodeId((int)$data['file_source']);
1012
+        $share->setNodeType($data['item_type']);
1013
+
1014
+        $share->setProviderId($this->identifier());
1015
+
1016
+        return $share;
1017
+    }
1018
+
1019
+    /**
1020
+     * Get the node with file $id for $user
1021
+     *
1022
+     * @param string $userId
1023
+     * @param int $id
1024
+     * @return \OCP\Files\File|\OCP\Files\Folder
1025
+     * @throws InvalidShare
1026
+     */
1027
+    private function getNode($userId, $id) {
1028
+        try {
1029
+            $userFolder = $this->rootFolder->getUserFolder($userId);
1030
+        } catch (NoUserException $e) {
1031
+            throw new InvalidShare();
1032
+        }
1033
+
1034
+        $nodes = $userFolder->getById($id);
1035
+
1036
+        if (empty($nodes)) {
1037
+            throw new InvalidShare();
1038
+        }
1039
+
1040
+        return $nodes[0];
1041
+    }
1042
+
1043
+    /**
1044
+     * A user is deleted from the system
1045
+     * So clean up the relevant shares.
1046
+     *
1047
+     * @param string $uid
1048
+     * @param int $shareType
1049
+     */
1050
+    public function userDeleted($uid, $shareType) {
1051
+        $qb = $this->dbConnection->getQueryBuilder();
1052
+
1053
+        $qb->delete('share')
1054
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
1055
+            ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
1056
+            ->execute();
1057
+    }
1058
+
1059
+    /**
1060
+     * This provider does not support group shares
1061
+     *
1062
+     * @param string $gid
1063
+     */
1064
+    public function groupDeleted($gid) {
1065
+    }
1066
+
1067
+    /**
1068
+     * This provider does not support group shares
1069
+     *
1070
+     * @param string $uid
1071
+     * @param string $gid
1072
+     */
1073
+    public function userDeletedFromGroup($uid, $gid) {
1074
+    }
1075
+
1076
+    /**
1077
+     * get database row of a give share
1078
+     *
1079
+     * @param $id
1080
+     * @return array
1081
+     * @throws ShareNotFound
1082
+     */
1083
+    protected function getRawShare($id) {
1084
+
1085
+        // Now fetch the inserted share and create a complete share object
1086
+        $qb = $this->dbConnection->getQueryBuilder();
1087
+        $qb->select('*')
1088
+            ->from('share')
1089
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
1090
+
1091
+        $cursor = $qb->execute();
1092
+        $data = $cursor->fetch();
1093
+        $cursor->closeCursor();
1094
+
1095
+        if ($data === false) {
1096
+            throw new ShareNotFound;
1097
+        }
1098
+
1099
+        return $data;
1100
+    }
1101
+
1102
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
1103
+        $qb = $this->dbConnection->getQueryBuilder();
1104
+        $qb->select('*')
1105
+            ->from('share', 's')
1106
+            ->andWhere($qb->expr()->orX(
1107
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1108
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1109
+            ))
1110
+            ->andWhere(
1111
+                $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
1112
+            );
1113
+
1114
+        /**
1115
+         * Reshares for this user are shares where they are the owner.
1116
+         */
1117
+        if ($reshares === false) {
1118
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
1119
+        } else {
1120
+            $qb->andWhere(
1121
+                $qb->expr()->orX(
1122
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
1123
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
1124
+                )
1125
+            );
1126
+        }
1127
+
1128
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
1129
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
1130
+
1131
+        $qb->orderBy('id');
1132
+
1133
+        $cursor = $qb->execute();
1134
+        $shares = [];
1135
+        while ($data = $cursor->fetch()) {
1136
+            $shares[$data['fileid']][] = $this->createShareObject($data);
1137
+        }
1138
+        $cursor->closeCursor();
1139
+
1140
+        return $shares;
1141
+    }
1142
+
1143
+    /**
1144
+     * @inheritdoc
1145
+     */
1146
+    public function getAccessList($nodes, $currentAccess) {
1147
+        $ids = [];
1148
+        foreach ($nodes as $node) {
1149
+            $ids[] = $node->getId();
1150
+        }
1151
+
1152
+        $qb = $this->dbConnection->getQueryBuilder();
1153
+        $qb->select('share_with')
1154
+            ->from('share')
1155
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
1156
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1157
+            ->andWhere($qb->expr()->orX(
1158
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1159
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1160
+            ))
1161
+            ->setMaxResults(1);
1162
+        $cursor = $qb->execute();
1163
+
1164
+        $mail = $cursor->fetch() !== false;
1165
+        $cursor->closeCursor();
1166
+
1167
+        return ['public' => $mail];
1168
+    }
1169 1169
 
1170 1170
 }
Please login to merge, or discard this patch.