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