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