Completed
Pull Request — master (#4303)
by Björn
35:10 queued 22:04
created
apps/sharebymail/lib/Settings/SettingsManager.php 1 patch
Indentation   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -27,35 +27,35 @@
 block discarded – undo
27 27
 
28 28
 class SettingsManager {
29 29
 
30
-	/** @var IConfig */
31
-	private $config;
32
-
33
-	private $sendPasswordByMailDefault = 'yes';
34
-
35
-	private $enforcePasswordProtectionDefault = 'no';
36
-
37
-	public function __construct(IConfig $config) {
38
-		$this->config = $config;
39
-	}
40
-
41
-	/**
42
-	 * should the password for a mail share be send to the recipient
43
-	 *
44
-	 * @return bool
45
-	 */
46
-	public function sendPasswordByMail() {
47
-		$sendPasswordByMail = $this->config->getAppValue('sharebymail', 'sendpasswordmail', $this->sendPasswordByMailDefault);
48
-		return $sendPasswordByMail === 'yes';
49
-	}
50
-
51
-	/**
52
-	 * do we require a share by mail to be password protected
53
-	 *
54
-	 * @return bool
55
-	 */
56
-	public function enforcePasswordProtection() {
57
-		$enforcePassword = $this->config->getAppValue('sharebymail', 'enforcePasswordProtection', $this->enforcePasswordProtectionDefault);
58
-		return $enforcePassword === 'yes';
59
-	}
30
+    /** @var IConfig */
31
+    private $config;
32
+
33
+    private $sendPasswordByMailDefault = 'yes';
34
+
35
+    private $enforcePasswordProtectionDefault = 'no';
36
+
37
+    public function __construct(IConfig $config) {
38
+        $this->config = $config;
39
+    }
40
+
41
+    /**
42
+     * should the password for a mail share be send to the recipient
43
+     *
44
+     * @return bool
45
+     */
46
+    public function sendPasswordByMail() {
47
+        $sendPasswordByMail = $this->config->getAppValue('sharebymail', 'sendpasswordmail', $this->sendPasswordByMailDefault);
48
+        return $sendPasswordByMail === 'yes';
49
+    }
50
+
51
+    /**
52
+     * do we require a share by mail to be password protected
53
+     *
54
+     * @return bool
55
+     */
56
+    public function enforcePasswordProtection() {
57
+        $enforcePassword = $this->config->getAppValue('sharebymail', 'enforcePasswordProtection', $this->enforcePasswordProtectionDefault);
58
+        return $enforcePassword === 'yes';
59
+    }
60 60
 
61 61
 }
Please login to merge, or discard this patch.
apps/sharebymail/lib/Settings/Admin.php 1 patch
Indentation   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -27,42 +27,42 @@
 block discarded – undo
27 27
 
28 28
 class Admin implements ISettings {
29 29
 
30
-	/** @var SettingsManager */
31
-	private $settingsManager;
30
+    /** @var SettingsManager */
31
+    private $settingsManager;
32 32
 
33
-	public function __construct(SettingsManager $settingsManager) {
34
-		$this->settingsManager = $settingsManager;
35
-	}
33
+    public function __construct(SettingsManager $settingsManager) {
34
+        $this->settingsManager = $settingsManager;
35
+    }
36 36
 
37
-	/**
38
-	 * @return TemplateResponse
39
-	 */
40
-	public function getForm() {
37
+    /**
38
+     * @return TemplateResponse
39
+     */
40
+    public function getForm() {
41 41
 
42
-		$parameters = [
43
-			'sendPasswordMail' => $this->settingsManager->sendPasswordByMail(),
44
-			'enforcePasswordProtection' => $this->settingsManager->enforcePasswordProtection()
45
-		];
42
+        $parameters = [
43
+            'sendPasswordMail' => $this->settingsManager->sendPasswordByMail(),
44
+            'enforcePasswordProtection' => $this->settingsManager->enforcePasswordProtection()
45
+        ];
46 46
 
47
-		return new TemplateResponse('sharebymail', 'settings-admin', $parameters, '');
48
-	}
47
+        return new TemplateResponse('sharebymail', 'settings-admin', $parameters, '');
48
+    }
49 49
 
50
-	/**
51
-	 * @return string the section ID, e.g. 'sharing'
52
-	 */
53
-	public function getSection() {
54
-		return 'sharing';
55
-	}
50
+    /**
51
+     * @return string the section ID, e.g. 'sharing'
52
+     */
53
+    public function getSection() {
54
+        return 'sharing';
55
+    }
56 56
 
57
-	/**
58
-	 * @return int whether the form should be rather on the top or bottom of
59
-	 * the admin section. The forms are arranged in ascending order of the
60
-	 * priority values. It is required to return a value between 0 and 100.
61
-	 *
62
-	 * E.g.: 70
63
-	 */
64
-	public function getPriority() {
65
-		return 40;
66
-	}
57
+    /**
58
+     * @return int whether the form should be rather on the top or bottom of
59
+     * the admin section. The forms are arranged in ascending order of the
60
+     * priority values. It is required to return a value between 0 and 100.
61
+     *
62
+     * E.g.: 70
63
+     */
64
+    public function getPriority() {
65
+        return 40;
66
+    }
67 67
 
68 68
 }
Please login to merge, or discard this patch.
apps/sharebymail/lib/Settings.php 1 patch
Indentation   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -27,27 +27,27 @@
 block discarded – undo
27 27
 
28 28
 class Settings {
29 29
 
30
-	/** @var SettingsManager */
31
-	private $settingsManager;
32
-
33
-	public function __construct(SettingsManager $settingsManager) {
34
-		$this->settingsManager = $settingsManager;
35
-	}
36
-
37
-	/**
38
-	 * announce that the share-by-mail share provider is enabled
39
-	 *
40
-	 * @param array $settings
41
-	 */
42
-	public function announceShareProvider(array $settings) {
43
-		$array = json_decode($settings['array']['oc_appconfig'], true);
44
-		$array['shareByMailEnabled'] = true;
45
-		$settings['array']['oc_appconfig'] = json_encode($array);
46
-	}
47
-
48
-	public function announceShareByMailSettings(array $settings) {
49
-		$array = json_decode($settings['array']['oc_appconfig'], true);
50
-		$array['shareByMail']['enforcePasswordProtection'] = $this->settingsManager->enforcePasswordProtection();
51
-		$settings['array']['oc_appconfig'] = json_encode($array);
52
-	}
30
+    /** @var SettingsManager */
31
+    private $settingsManager;
32
+
33
+    public function __construct(SettingsManager $settingsManager) {
34
+        $this->settingsManager = $settingsManager;
35
+    }
36
+
37
+    /**
38
+     * announce that the share-by-mail share provider is enabled
39
+     *
40
+     * @param array $settings
41
+     */
42
+    public function announceShareProvider(array $settings) {
43
+        $array = json_decode($settings['array']['oc_appconfig'], true);
44
+        $array['shareByMailEnabled'] = true;
45
+        $settings['array']['oc_appconfig'] = json_encode($array);
46
+    }
47
+
48
+    public function announceShareByMailSettings(array $settings) {
49
+        $array = json_decode($settings['array']['oc_appconfig'], true);
50
+        $array['shareByMail']['enforcePasswordProtection'] = $this->settingsManager->enforcePasswordProtection();
51
+        $settings['array']['oc_appconfig'] = json_encode($array);
52
+    }
53 53
 }
Please login to merge, or discard this patch.
apps/sharebymail/lib/AppInfo/Application.php 1 patch
Indentation   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -29,19 +29,19 @@
 block discarded – undo
29 29
 
30 30
 class Application extends App {
31 31
 
32
-	public function __construct(array $urlParams = array()) {
33
-		parent::__construct('sharebymail', $urlParams);
32
+    public function __construct(array $urlParams = array()) {
33
+        parent::__construct('sharebymail', $urlParams);
34 34
 
35
-		$settingsManager = \OC::$server->query(Settings\SettingsManager::class);
36
-		$settings = new Settings($settingsManager);
35
+        $settingsManager = \OC::$server->query(Settings\SettingsManager::class);
36
+        $settings = new Settings($settingsManager);
37 37
 
38
-		/** register capabilities */
39
-		$container = $this->getContainer();
40
-		$container->registerCapability('OCA\ShareByMail\Capabilities');
38
+        /** register capabilities */
39
+        $container = $this->getContainer();
40
+        $container->registerCapability('OCA\ShareByMail\Capabilities');
41 41
 
42
-		/** register hooks */
43
-		Util::connectHook('\OCP\Config', 'js', $settings, 'announceShareProvider');
44
-		Util::connectHook('\OCP\Config', 'js', $settings, 'announceShareByMailSettings');
45
-	}
42
+        /** register hooks */
43
+        Util::connectHook('\OCP\Config', 'js', $settings, 'announceShareProvider');
44
+        Util::connectHook('\OCP\Config', 'js', $settings, 'announceShareByMailSettings');
45
+    }
46 46
 
47 47
 }
Please login to merge, or discard this patch.
apps/sharebymail/lib/ShareByMailProvider.php 1 patch
Indentation   +863 added lines, -863 removed lines patch added patch discarded remove patch
@@ -51,881 +51,881 @@
 block discarded – undo
51 51
  */
52 52
 class ShareByMailProvider implements IShareProvider {
53 53
 
54
-	/** @var  IDBConnection */
55
-	private $dbConnection;
56
-
57
-	/** @var ILogger */
58
-	private $logger;
59
-
60
-	/** @var ISecureRandom */
61
-	private $secureRandom;
62
-
63
-	/** @var IUserManager */
64
-	private $userManager;
65
-
66
-	/** @var IRootFolder */
67
-	private $rootFolder;
68
-
69
-	/** @var IL10N */
70
-	private $l;
71
-
72
-	/** @var IMailer */
73
-	private $mailer;
74
-
75
-	/** @var IURLGenerator */
76
-	private $urlGenerator;
77
-
78
-	/** @var IManager  */
79
-	private $activityManager;
80
-
81
-	/** @var SettingsManager */
82
-	private $settingsManager;
83
-
84
-	/** @var IHasher */
85
-	private $hasher;
86
-
87
-	/**
88
-	 * Return the identifier of this provider.
89
-	 *
90
-	 * @return string Containing only [a-zA-Z0-9]
91
-	 */
92
-	public function identifier() {
93
-		return 'ocMailShare';
94
-	}
95
-
96
-	/**
97
-	 * DefaultShareProvider constructor.
98
-	 *
99
-	 * @param IDBConnection $connection
100
-	 * @param ISecureRandom $secureRandom
101
-	 * @param IUserManager $userManager
102
-	 * @param IRootFolder $rootFolder
103
-	 * @param IL10N $l
104
-	 * @param ILogger $logger
105
-	 * @param IMailer $mailer
106
-	 * @param IURLGenerator $urlGenerator
107
-	 * @param IManager $activityManager
108
-	 * @param SettingsManager $settingsManager
109
-	 * @param IHasher $hasher
110
-	 */
111
-	public function __construct(
112
-		IDBConnection $connection,
113
-		ISecureRandom $secureRandom,
114
-		IUserManager $userManager,
115
-		IRootFolder $rootFolder,
116
-		IL10N $l,
117
-		ILogger $logger,
118
-		IMailer $mailer,
119
-		IURLGenerator $urlGenerator,
120
-		IManager $activityManager,
121
-		SettingsManager $settingsManager,
122
-		IHasher $hasher
123
-	) {
124
-		$this->dbConnection = $connection;
125
-		$this->secureRandom = $secureRandom;
126
-		$this->userManager = $userManager;
127
-		$this->rootFolder = $rootFolder;
128
-		$this->l = $l;
129
-		$this->logger = $logger;
130
-		$this->mailer = $mailer;
131
-		$this->urlGenerator = $urlGenerator;
132
-		$this->activityManager = $activityManager;
133
-		$this->settingsManager = $settingsManager;
134
-		$this->hasher = $hasher;
135
-	}
136
-
137
-	/**
138
-	 * Share a path
139
-	 *
140
-	 * @param IShare $share
141
-	 * @return IShare The share object
142
-	 * @throws ShareNotFound
143
-	 * @throws \Exception
144
-	 */
145
-	public function create(IShare $share) {
146
-
147
-		$shareWith = $share->getSharedWith();
148
-		/*
54
+    /** @var  IDBConnection */
55
+    private $dbConnection;
56
+
57
+    /** @var ILogger */
58
+    private $logger;
59
+
60
+    /** @var ISecureRandom */
61
+    private $secureRandom;
62
+
63
+    /** @var IUserManager */
64
+    private $userManager;
65
+
66
+    /** @var IRootFolder */
67
+    private $rootFolder;
68
+
69
+    /** @var IL10N */
70
+    private $l;
71
+
72
+    /** @var IMailer */
73
+    private $mailer;
74
+
75
+    /** @var IURLGenerator */
76
+    private $urlGenerator;
77
+
78
+    /** @var IManager  */
79
+    private $activityManager;
80
+
81
+    /** @var SettingsManager */
82
+    private $settingsManager;
83
+
84
+    /** @var IHasher */
85
+    private $hasher;
86
+
87
+    /**
88
+     * Return the identifier of this provider.
89
+     *
90
+     * @return string Containing only [a-zA-Z0-9]
91
+     */
92
+    public function identifier() {
93
+        return 'ocMailShare';
94
+    }
95
+
96
+    /**
97
+     * DefaultShareProvider constructor.
98
+     *
99
+     * @param IDBConnection $connection
100
+     * @param ISecureRandom $secureRandom
101
+     * @param IUserManager $userManager
102
+     * @param IRootFolder $rootFolder
103
+     * @param IL10N $l
104
+     * @param ILogger $logger
105
+     * @param IMailer $mailer
106
+     * @param IURLGenerator $urlGenerator
107
+     * @param IManager $activityManager
108
+     * @param SettingsManager $settingsManager
109
+     * @param IHasher $hasher
110
+     */
111
+    public function __construct(
112
+        IDBConnection $connection,
113
+        ISecureRandom $secureRandom,
114
+        IUserManager $userManager,
115
+        IRootFolder $rootFolder,
116
+        IL10N $l,
117
+        ILogger $logger,
118
+        IMailer $mailer,
119
+        IURLGenerator $urlGenerator,
120
+        IManager $activityManager,
121
+        SettingsManager $settingsManager,
122
+        IHasher $hasher
123
+    ) {
124
+        $this->dbConnection = $connection;
125
+        $this->secureRandom = $secureRandom;
126
+        $this->userManager = $userManager;
127
+        $this->rootFolder = $rootFolder;
128
+        $this->l = $l;
129
+        $this->logger = $logger;
130
+        $this->mailer = $mailer;
131
+        $this->urlGenerator = $urlGenerator;
132
+        $this->activityManager = $activityManager;
133
+        $this->settingsManager = $settingsManager;
134
+        $this->hasher = $hasher;
135
+    }
136
+
137
+    /**
138
+     * Share a path
139
+     *
140
+     * @param IShare $share
141
+     * @return IShare The share object
142
+     * @throws ShareNotFound
143
+     * @throws \Exception
144
+     */
145
+    public function create(IShare $share) {
146
+
147
+        $shareWith = $share->getSharedWith();
148
+        /*
149 149
 		 * Check if file is not already shared with the remote user
150 150
 		 */
151
-		$alreadyShared = $this->getSharedWith($shareWith, \OCP\Share::SHARE_TYPE_EMAIL, $share->getNode(), 1, 0);
152
-		if (!empty($alreadyShared)) {
153
-			$message = 'Sharing %s failed, this item is already shared with %s';
154
-			$message_t = $this->l->t('Sharing %s failed, this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
155
-			$this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
156
-			throw new \Exception($message_t);
157
-		}
158
-
159
-		// if the admin enforces a password for all mail shares we create a
160
-		// random password and send it to the recipient
161
-		$password = '';
162
-		$passwordEnforced = $this->settingsManager->enforcePasswordProtection();
163
-		if ($passwordEnforced) {
164
-			$password = $this->autoGeneratePassword($share);
165
-		}
166
-
167
-		$shareId = $this->createMailShare($share);
168
-		$send = $this->sendPassword($share->getNode()->getName(), $share->getSharedBy(), $share->getSharedWith(), $password);
169
-		if ($passwordEnforced && $send === false) {
170
-			$this->sendPasswordToOwner($share->getNode()->getName(), $share->getSharedBy(), $shareWith, $password);
171
-		}
172
-		$this->createActivity($share);
173
-		$data = $this->getRawShare($shareId);
174
-
175
-		return $this->createShareObject($data);
176
-
177
-	}
178
-
179
-	/**
180
-	 * auto generate password in case of password enforcement on mail shares
181
-	 *
182
-	 * @param IShare $share
183
-	 * @return string
184
-	 * @throws \Exception
185
-	 */
186
-	protected function autoGeneratePassword($share) {
187
-		$initiatorUser = $this->userManager->get($share->getSharedBy());
188
-		$initiatorEMailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
189
-		$allowPasswordByMail = $this->settingsManager->sendPasswordByMail();
190
-
191
-		if ($initiatorEMailAddress === null && !$allowPasswordByMail) {
192
-			throw new \Exception(
193
-				$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.")
194
-			);
195
-		}
196
-
197
-		$password = $this->generateToken(8);
198
-		$share->setPassword($this->hasher->hash($password));
199
-
200
-		return $password;
201
-	}
202
-
203
-	/**
204
-	 * create activity if a file/folder was shared by mail
205
-	 *
206
-	 * @param IShare $share
207
-	 */
208
-	protected function createActivity(IShare $share) {
209
-
210
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
211
-
212
-		$this->publishActivity(
213
-			Activity::SUBJECT_SHARED_EMAIL_SELF,
214
-			[$userFolder->getRelativePath($share->getNode()->getPath()), $share->getSharedWith()],
215
-			$share->getSharedBy(),
216
-			$share->getNode()->getId(),
217
-			$userFolder->getRelativePath($share->getNode()->getPath())
218
-		);
219
-
220
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
221
-			$ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
222
-			$fileId = $share->getNode()->getId();
223
-			$nodes = $ownerFolder->getById($fileId);
224
-			$ownerPath = $nodes[0]->getPath();
225
-			$this->publishActivity(
226
-				Activity::SUBJECT_SHARED_EMAIL_BY,
227
-				[$ownerFolder->getRelativePath($ownerPath), $share->getSharedWith(), $share->getSharedBy()],
228
-				$share->getShareOwner(),
229
-				$fileId,
230
-				$ownerFolder->getRelativePath($ownerPath)
231
-			);
232
-		}
233
-
234
-	}
235
-
236
-	/**
237
-	 * publish activity if a file/folder was shared by mail
238
-	 *
239
-	 * @param $subject
240
-	 * @param $parameters
241
-	 * @param $affectedUser
242
-	 * @param $fileId
243
-	 * @param $filePath
244
-	 */
245
-	protected function publishActivity($subject, $parameters, $affectedUser, $fileId, $filePath) {
246
-		$event = $this->activityManager->generateEvent();
247
-		$event->setApp('sharebymail')
248
-			->setType('shared')
249
-			->setSubject($subject, $parameters)
250
-			->setAffectedUser($affectedUser)
251
-			->setObject('files', $fileId, $filePath);
252
-		$this->activityManager->publish($event);
253
-
254
-	}
255
-
256
-	/**
257
-	 * @param IShare $share
258
-	 * @return int
259
-	 * @throws \Exception
260
-	 */
261
-	protected function createMailShare(IShare $share) {
262
-		$share->setToken($this->generateToken());
263
-		$shareId = $this->addShareToDB(
264
-			$share->getNodeId(),
265
-			$share->getNodeType(),
266
-			$share->getSharedWith(),
267
-			$share->getSharedBy(),
268
-			$share->getShareOwner(),
269
-			$share->getPermissions(),
270
-			$share->getToken(),
271
-			$share->getPassword()
272
-		);
273
-
274
-		try {
275
-			$link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
276
-				['token' => $share->getToken()]);
277
-			$this->sendMailNotification($share->getNode()->getName(),
278
-				$link,
279
-				$share->getShareOwner(),
280
-				$share->getSharedBy(), $share->getSharedWith());
281
-		} catch (HintException $hintException) {
282
-			$this->logger->error('Failed to send share by mail: ' . $hintException->getMessage());
283
-			$this->removeShareFromTable($shareId);
284
-			throw $hintException;
285
-		} catch (\Exception $e) {
286
-			$this->logger->error('Failed to send share by mail: ' . $e->getMessage());
287
-			$this->removeShareFromTable($shareId);
288
-			throw new HintException('Failed to send share by mail',
289
-				$this->l->t('Failed to send share by E-mail'));
290
-		}
291
-
292
-		return $shareId;
293
-
294
-	}
295
-
296
-	protected function sendMailNotification($filename, $link, $owner, $initiator, $shareWith) {
297
-		$ownerUser = $this->userManager->get($owner);
298
-		$initiatorUser = $this->userManager->get($initiator);
299
-		$ownerDisplayName = ($ownerUser instanceof IUser) ? $ownerUser->getDisplayName() : $owner;
300
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
301
-		$initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
302
-		if ($owner === $initiator) {
303
-			$subject = (string)$this->l->t('%s shared »%s« with you', array($ownerDisplayName, $filename));
304
-		} else {
305
-			$subject = (string)$this->l->t('%s shared »%s« with you on behalf of %s', array($ownerDisplayName, $filename, $initiatorDisplayName));
306
-		}
307
-
308
-		$message = $this->mailer->createMessage();
309
-
310
-		$emailTemplate = $this->mailer->createEMailTemplate();
311
-
312
-		$emailTemplate->addHeader();
313
-		$emailTemplate->addHeading($this->l->t('%s shared »%s« with you', [$ownerDisplayName, $filename]), false);
314
-		if ($owner === $initiator) {
315
-			$text = $this->l->t('%s shared »%s« with you.', [$ownerDisplayName, $filename]);
316
-		} else {
317
-			$text= $this->l->t('%s shared »%s« with you on behalf of %s.', [$ownerDisplayName, $filename, $initiator]);
318
-		}
319
-		$emailTemplate->addBodyText(
320
-			$text . ' ' . $this->l->t('Click the button below to open it.'),
321
-			$text
322
-		);
323
-		$emailTemplate->addBodyButton(
324
-			$this->l->t('Open »%s«', [$filename]),
325
-			$link
326
-		);
327
-		$emailTemplate->addFooter();
328
-		if ($initiatorEmailAddress !== null) {
329
-			$message->setFrom([$initiatorEmailAddress => $initiatorDisplayName]);
330
-		}
331
-		$message->setTo([$shareWith]);
332
-		$message->setSubject($subject);
333
-		$message->setBody($emailTemplate->renderText(), 'text/plain');
334
-		$message->setHtmlBody($emailTemplate->renderHTML());
335
-		$this->mailer->send($message);
336
-	}
337
-
338
-	/**
339
-	 * send password to recipient of a mail share
340
-	 *
341
-	 * @param string $filename
342
-	 * @param string $initiator
343
-	 * @param string $shareWith
344
-	 * @param string $password
345
-	 * @return bool
346
-	 */
347
-	protected function sendPassword($filename, $initiator, $shareWith, $password) {
348
-
349
-		if ($password === '' || $this->settingsManager->sendPasswordByMail() === false) {
350
-			return false;
351
-		}
352
-
353
-		$initiatorUser = $this->userManager->get($initiator);
354
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
355
-		$initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
356
-
357
-		$subject = (string)$this->l->t('Password to access »%s« shared to you by %s', [$filename, $initiatorDisplayName]);
358
-		$plainBodyPart = $this->l->t("%s shared »%s« with you.\nYou should have already received a separate mail with a link to access it.\n", [$initiatorDisplayName, $filename]);
359
-		$htmlBodyPart = $this->l->t('%s shared »%s« with you. You should have already received a separate mail with a link to access it.', [$initiatorDisplayName, $filename]);
360
-
361
-		$message = $this->mailer->createMessage();
362
-
363
-		$emailTemplate = $this->mailer->createEMailTemplate();
364
-		$emailTemplate->addHeader();
365
-		$emailTemplate->addHeading($this->l->t('Password to access »%s«', [$filename]), false);
366
-		$emailTemplate->addBodyText($htmlBodyPart, $plainBodyPart);
367
-		$emailTemplate->addBodyText($this->l->t('It is protected with the following password: %s', [$password]));
368
-		$emailTemplate->addFooter();
369
-
370
-		if ($initiatorEmailAddress !== null) {
371
-			$message->setFrom([$initiatorEmailAddress => $initiatorDisplayName]);
372
-		}
373
-		$message->setTo([$shareWith]);
374
-		$message->setSubject($subject);
375
-		$message->setBody($emailTemplate->renderText(), 'text/plain');
376
-		$message->setHtmlBody($emailTemplate->renderHTML());
377
-		$this->mailer->send($message);
378
-
379
-		return true;
380
-	}
381
-
382
-	/**
383
-	 * send auto generated password to the owner. This happens if the admin enforces
384
-	 * a password for mail shares and forbid to send the password by mail to the recipient
385
-	 *
386
-	 * @param string $filename
387
-	 * @param string $initiator
388
-	 * @param string $shareWith
389
-	 * @param string $password
390
-	 * @throws \Exception
391
-	 */
392
-	protected function sendPasswordToOwner($filename, $initiator, $shareWith, $password) {
393
-
394
-		$initiatorUser = $this->userManager->get($initiator);
395
-		$initiatorEMailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
396
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
397
-
398
-		if ($initiatorEMailAddress === null) {
399
-			throw new \Exception(
400
-				$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.")
401
-			);
402
-		}
403
-
404
-		$subject = (string)$this->l->t('Password to access »%s« shared with %s', [$filename, $shareWith]);
405
-		$plainBodyPart = $this->l->t("You just shared »%s« with %s.\nThe share was already send to the recipient. Due to the security policies\neach share needs to be protected by password and it is not allowed to send the\npassword directly by mail to the recipient. Therefore you need to forward\nthe password manually to the recipient.", [$filename, $shareWith]);
406
-		$htmlBodyPart = $this->l->t('You just shared »%s« with %s. The share was already send to the recipient. Due to the security policies each share needs to be protected by password and it is not allowed to send the password directly by mail to the recipient. Therefore you need to forward the password manually to the recipient.', [$filename, $shareWith]);
407
-
408
-		$message = $this->mailer->createMessage();
409
-		$emailTemplate = $this->mailer->createEMailTemplate();
410
-
411
-		$emailTemplate->addHeader();
412
-		$emailTemplate->addHeading($this->l->t('Password to access »%s«', [$filename]), false);
413
-		$emailTemplate->addBodyText($htmlBodyPart, $plainBodyPart);
414
-		$emailTemplate->addBodyText($this->l->t('This is the password: %s', [$password]));
415
-		$emailTemplate->addBodyText($this->l->t('You can chose a different password at any time in the share dialog.'));
416
-		$emailTemplate->addFooter();
417
-
418
-		if ($initiatorEMailAddress) {
419
-			$message->setFrom([$initiatorEMailAddress => $initiatorDisplayName]);
420
-		}
421
-		$message->setTo([$initiatorEMailAddress => $initiatorDisplayName]);
422
-		$message->setSubject($subject);
423
-		$message->setBody($emailTemplate->renderText(), 'text/plain');
424
-		$message->setHtmlBody($emailTemplate->renderHTML());
425
-		$this->mailer->send($message);
426
-	}
427
-
428
-	/**
429
-	 * generate share token
430
-	 *
431
-	 * @return string
432
-	 */
433
-	protected function generateToken($size = 15) {
434
-		$token = $this->secureRandom->generate(
435
-			$size, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);
436
-		return $token;
437
-	}
438
-
439
-	/**
440
-	 * Get all children of this share
441
-	 *
442
-	 * @param IShare $parent
443
-	 * @return IShare[]
444
-	 */
445
-	public function getChildren(IShare $parent) {
446
-		$children = [];
447
-
448
-		$qb = $this->dbConnection->getQueryBuilder();
449
-		$qb->select('*')
450
-			->from('share')
451
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
452
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
453
-			->orderBy('id');
454
-
455
-		$cursor = $qb->execute();
456
-		while($data = $cursor->fetch()) {
457
-			$children[] = $this->createShareObject($data);
458
-		}
459
-		$cursor->closeCursor();
460
-
461
-		return $children;
462
-	}
463
-
464
-	/**
465
-	 * add share to the database and return the ID
466
-	 *
467
-	 * @param int $itemSource
468
-	 * @param string $itemType
469
-	 * @param string $shareWith
470
-	 * @param string $sharedBy
471
-	 * @param string $uidOwner
472
-	 * @param int $permissions
473
-	 * @param string $token
474
-	 * @return int
475
-	 */
476
-	protected function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token, $password) {
477
-		$qb = $this->dbConnection->getQueryBuilder();
478
-		$qb->insert('share')
479
-			->setValue('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
480
-			->setValue('item_type', $qb->createNamedParameter($itemType))
481
-			->setValue('item_source', $qb->createNamedParameter($itemSource))
482
-			->setValue('file_source', $qb->createNamedParameter($itemSource))
483
-			->setValue('share_with', $qb->createNamedParameter($shareWith))
484
-			->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
485
-			->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
486
-			->setValue('permissions', $qb->createNamedParameter($permissions))
487
-			->setValue('token', $qb->createNamedParameter($token))
488
-			->setValue('password', $qb->createNamedParameter($password))
489
-			->setValue('stime', $qb->createNamedParameter(time()));
490
-
491
-		/*
151
+        $alreadyShared = $this->getSharedWith($shareWith, \OCP\Share::SHARE_TYPE_EMAIL, $share->getNode(), 1, 0);
152
+        if (!empty($alreadyShared)) {
153
+            $message = 'Sharing %s failed, this item is already shared with %s';
154
+            $message_t = $this->l->t('Sharing %s failed, this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
155
+            $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
156
+            throw new \Exception($message_t);
157
+        }
158
+
159
+        // if the admin enforces a password for all mail shares we create a
160
+        // random password and send it to the recipient
161
+        $password = '';
162
+        $passwordEnforced = $this->settingsManager->enforcePasswordProtection();
163
+        if ($passwordEnforced) {
164
+            $password = $this->autoGeneratePassword($share);
165
+        }
166
+
167
+        $shareId = $this->createMailShare($share);
168
+        $send = $this->sendPassword($share->getNode()->getName(), $share->getSharedBy(), $share->getSharedWith(), $password);
169
+        if ($passwordEnforced && $send === false) {
170
+            $this->sendPasswordToOwner($share->getNode()->getName(), $share->getSharedBy(), $shareWith, $password);
171
+        }
172
+        $this->createActivity($share);
173
+        $data = $this->getRawShare($shareId);
174
+
175
+        return $this->createShareObject($data);
176
+
177
+    }
178
+
179
+    /**
180
+     * auto generate password in case of password enforcement on mail shares
181
+     *
182
+     * @param IShare $share
183
+     * @return string
184
+     * @throws \Exception
185
+     */
186
+    protected function autoGeneratePassword($share) {
187
+        $initiatorUser = $this->userManager->get($share->getSharedBy());
188
+        $initiatorEMailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
189
+        $allowPasswordByMail = $this->settingsManager->sendPasswordByMail();
190
+
191
+        if ($initiatorEMailAddress === null && !$allowPasswordByMail) {
192
+            throw new \Exception(
193
+                $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.")
194
+            );
195
+        }
196
+
197
+        $password = $this->generateToken(8);
198
+        $share->setPassword($this->hasher->hash($password));
199
+
200
+        return $password;
201
+    }
202
+
203
+    /**
204
+     * create activity if a file/folder was shared by mail
205
+     *
206
+     * @param IShare $share
207
+     */
208
+    protected function createActivity(IShare $share) {
209
+
210
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
211
+
212
+        $this->publishActivity(
213
+            Activity::SUBJECT_SHARED_EMAIL_SELF,
214
+            [$userFolder->getRelativePath($share->getNode()->getPath()), $share->getSharedWith()],
215
+            $share->getSharedBy(),
216
+            $share->getNode()->getId(),
217
+            $userFolder->getRelativePath($share->getNode()->getPath())
218
+        );
219
+
220
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
221
+            $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
222
+            $fileId = $share->getNode()->getId();
223
+            $nodes = $ownerFolder->getById($fileId);
224
+            $ownerPath = $nodes[0]->getPath();
225
+            $this->publishActivity(
226
+                Activity::SUBJECT_SHARED_EMAIL_BY,
227
+                [$ownerFolder->getRelativePath($ownerPath), $share->getSharedWith(), $share->getSharedBy()],
228
+                $share->getShareOwner(),
229
+                $fileId,
230
+                $ownerFolder->getRelativePath($ownerPath)
231
+            );
232
+        }
233
+
234
+    }
235
+
236
+    /**
237
+     * publish activity if a file/folder was shared by mail
238
+     *
239
+     * @param $subject
240
+     * @param $parameters
241
+     * @param $affectedUser
242
+     * @param $fileId
243
+     * @param $filePath
244
+     */
245
+    protected function publishActivity($subject, $parameters, $affectedUser, $fileId, $filePath) {
246
+        $event = $this->activityManager->generateEvent();
247
+        $event->setApp('sharebymail')
248
+            ->setType('shared')
249
+            ->setSubject($subject, $parameters)
250
+            ->setAffectedUser($affectedUser)
251
+            ->setObject('files', $fileId, $filePath);
252
+        $this->activityManager->publish($event);
253
+
254
+    }
255
+
256
+    /**
257
+     * @param IShare $share
258
+     * @return int
259
+     * @throws \Exception
260
+     */
261
+    protected function createMailShare(IShare $share) {
262
+        $share->setToken($this->generateToken());
263
+        $shareId = $this->addShareToDB(
264
+            $share->getNodeId(),
265
+            $share->getNodeType(),
266
+            $share->getSharedWith(),
267
+            $share->getSharedBy(),
268
+            $share->getShareOwner(),
269
+            $share->getPermissions(),
270
+            $share->getToken(),
271
+            $share->getPassword()
272
+        );
273
+
274
+        try {
275
+            $link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
276
+                ['token' => $share->getToken()]);
277
+            $this->sendMailNotification($share->getNode()->getName(),
278
+                $link,
279
+                $share->getShareOwner(),
280
+                $share->getSharedBy(), $share->getSharedWith());
281
+        } catch (HintException $hintException) {
282
+            $this->logger->error('Failed to send share by mail: ' . $hintException->getMessage());
283
+            $this->removeShareFromTable($shareId);
284
+            throw $hintException;
285
+        } catch (\Exception $e) {
286
+            $this->logger->error('Failed to send share by mail: ' . $e->getMessage());
287
+            $this->removeShareFromTable($shareId);
288
+            throw new HintException('Failed to send share by mail',
289
+                $this->l->t('Failed to send share by E-mail'));
290
+        }
291
+
292
+        return $shareId;
293
+
294
+    }
295
+
296
+    protected function sendMailNotification($filename, $link, $owner, $initiator, $shareWith) {
297
+        $ownerUser = $this->userManager->get($owner);
298
+        $initiatorUser = $this->userManager->get($initiator);
299
+        $ownerDisplayName = ($ownerUser instanceof IUser) ? $ownerUser->getDisplayName() : $owner;
300
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
301
+        $initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
302
+        if ($owner === $initiator) {
303
+            $subject = (string)$this->l->t('%s shared »%s« with you', array($ownerDisplayName, $filename));
304
+        } else {
305
+            $subject = (string)$this->l->t('%s shared »%s« with you on behalf of %s', array($ownerDisplayName, $filename, $initiatorDisplayName));
306
+        }
307
+
308
+        $message = $this->mailer->createMessage();
309
+
310
+        $emailTemplate = $this->mailer->createEMailTemplate();
311
+
312
+        $emailTemplate->addHeader();
313
+        $emailTemplate->addHeading($this->l->t('%s shared »%s« with you', [$ownerDisplayName, $filename]), false);
314
+        if ($owner === $initiator) {
315
+            $text = $this->l->t('%s shared »%s« with you.', [$ownerDisplayName, $filename]);
316
+        } else {
317
+            $text= $this->l->t('%s shared »%s« with you on behalf of %s.', [$ownerDisplayName, $filename, $initiator]);
318
+        }
319
+        $emailTemplate->addBodyText(
320
+            $text . ' ' . $this->l->t('Click the button below to open it.'),
321
+            $text
322
+        );
323
+        $emailTemplate->addBodyButton(
324
+            $this->l->t('Open »%s«', [$filename]),
325
+            $link
326
+        );
327
+        $emailTemplate->addFooter();
328
+        if ($initiatorEmailAddress !== null) {
329
+            $message->setFrom([$initiatorEmailAddress => $initiatorDisplayName]);
330
+        }
331
+        $message->setTo([$shareWith]);
332
+        $message->setSubject($subject);
333
+        $message->setBody($emailTemplate->renderText(), 'text/plain');
334
+        $message->setHtmlBody($emailTemplate->renderHTML());
335
+        $this->mailer->send($message);
336
+    }
337
+
338
+    /**
339
+     * send password to recipient of a mail share
340
+     *
341
+     * @param string $filename
342
+     * @param string $initiator
343
+     * @param string $shareWith
344
+     * @param string $password
345
+     * @return bool
346
+     */
347
+    protected function sendPassword($filename, $initiator, $shareWith, $password) {
348
+
349
+        if ($password === '' || $this->settingsManager->sendPasswordByMail() === false) {
350
+            return false;
351
+        }
352
+
353
+        $initiatorUser = $this->userManager->get($initiator);
354
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
355
+        $initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
356
+
357
+        $subject = (string)$this->l->t('Password to access »%s« shared to you by %s', [$filename, $initiatorDisplayName]);
358
+        $plainBodyPart = $this->l->t("%s shared »%s« with you.\nYou should have already received a separate mail with a link to access it.\n", [$initiatorDisplayName, $filename]);
359
+        $htmlBodyPart = $this->l->t('%s shared »%s« with you. You should have already received a separate mail with a link to access it.', [$initiatorDisplayName, $filename]);
360
+
361
+        $message = $this->mailer->createMessage();
362
+
363
+        $emailTemplate = $this->mailer->createEMailTemplate();
364
+        $emailTemplate->addHeader();
365
+        $emailTemplate->addHeading($this->l->t('Password to access »%s«', [$filename]), false);
366
+        $emailTemplate->addBodyText($htmlBodyPart, $plainBodyPart);
367
+        $emailTemplate->addBodyText($this->l->t('It is protected with the following password: %s', [$password]));
368
+        $emailTemplate->addFooter();
369
+
370
+        if ($initiatorEmailAddress !== null) {
371
+            $message->setFrom([$initiatorEmailAddress => $initiatorDisplayName]);
372
+        }
373
+        $message->setTo([$shareWith]);
374
+        $message->setSubject($subject);
375
+        $message->setBody($emailTemplate->renderText(), 'text/plain');
376
+        $message->setHtmlBody($emailTemplate->renderHTML());
377
+        $this->mailer->send($message);
378
+
379
+        return true;
380
+    }
381
+
382
+    /**
383
+     * send auto generated password to the owner. This happens if the admin enforces
384
+     * a password for mail shares and forbid to send the password by mail to the recipient
385
+     *
386
+     * @param string $filename
387
+     * @param string $initiator
388
+     * @param string $shareWith
389
+     * @param string $password
390
+     * @throws \Exception
391
+     */
392
+    protected function sendPasswordToOwner($filename, $initiator, $shareWith, $password) {
393
+
394
+        $initiatorUser = $this->userManager->get($initiator);
395
+        $initiatorEMailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
396
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
397
+
398
+        if ($initiatorEMailAddress === null) {
399
+            throw new \Exception(
400
+                $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.")
401
+            );
402
+        }
403
+
404
+        $subject = (string)$this->l->t('Password to access »%s« shared with %s', [$filename, $shareWith]);
405
+        $plainBodyPart = $this->l->t("You just shared »%s« with %s.\nThe share was already send to the recipient. Due to the security policies\neach share needs to be protected by password and it is not allowed to send the\npassword directly by mail to the recipient. Therefore you need to forward\nthe password manually to the recipient.", [$filename, $shareWith]);
406
+        $htmlBodyPart = $this->l->t('You just shared »%s« with %s. The share was already send to the recipient. Due to the security policies each share needs to be protected by password and it is not allowed to send the password directly by mail to the recipient. Therefore you need to forward the password manually to the recipient.', [$filename, $shareWith]);
407
+
408
+        $message = $this->mailer->createMessage();
409
+        $emailTemplate = $this->mailer->createEMailTemplate();
410
+
411
+        $emailTemplate->addHeader();
412
+        $emailTemplate->addHeading($this->l->t('Password to access »%s«', [$filename]), false);
413
+        $emailTemplate->addBodyText($htmlBodyPart, $plainBodyPart);
414
+        $emailTemplate->addBodyText($this->l->t('This is the password: %s', [$password]));
415
+        $emailTemplate->addBodyText($this->l->t('You can chose a different password at any time in the share dialog.'));
416
+        $emailTemplate->addFooter();
417
+
418
+        if ($initiatorEMailAddress) {
419
+            $message->setFrom([$initiatorEMailAddress => $initiatorDisplayName]);
420
+        }
421
+        $message->setTo([$initiatorEMailAddress => $initiatorDisplayName]);
422
+        $message->setSubject($subject);
423
+        $message->setBody($emailTemplate->renderText(), 'text/plain');
424
+        $message->setHtmlBody($emailTemplate->renderHTML());
425
+        $this->mailer->send($message);
426
+    }
427
+
428
+    /**
429
+     * generate share token
430
+     *
431
+     * @return string
432
+     */
433
+    protected function generateToken($size = 15) {
434
+        $token = $this->secureRandom->generate(
435
+            $size, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);
436
+        return $token;
437
+    }
438
+
439
+    /**
440
+     * Get all children of this share
441
+     *
442
+     * @param IShare $parent
443
+     * @return IShare[]
444
+     */
445
+    public function getChildren(IShare $parent) {
446
+        $children = [];
447
+
448
+        $qb = $this->dbConnection->getQueryBuilder();
449
+        $qb->select('*')
450
+            ->from('share')
451
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
452
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
453
+            ->orderBy('id');
454
+
455
+        $cursor = $qb->execute();
456
+        while($data = $cursor->fetch()) {
457
+            $children[] = $this->createShareObject($data);
458
+        }
459
+        $cursor->closeCursor();
460
+
461
+        return $children;
462
+    }
463
+
464
+    /**
465
+     * add share to the database and return the ID
466
+     *
467
+     * @param int $itemSource
468
+     * @param string $itemType
469
+     * @param string $shareWith
470
+     * @param string $sharedBy
471
+     * @param string $uidOwner
472
+     * @param int $permissions
473
+     * @param string $token
474
+     * @return int
475
+     */
476
+    protected function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token, $password) {
477
+        $qb = $this->dbConnection->getQueryBuilder();
478
+        $qb->insert('share')
479
+            ->setValue('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
480
+            ->setValue('item_type', $qb->createNamedParameter($itemType))
481
+            ->setValue('item_source', $qb->createNamedParameter($itemSource))
482
+            ->setValue('file_source', $qb->createNamedParameter($itemSource))
483
+            ->setValue('share_with', $qb->createNamedParameter($shareWith))
484
+            ->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
485
+            ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
486
+            ->setValue('permissions', $qb->createNamedParameter($permissions))
487
+            ->setValue('token', $qb->createNamedParameter($token))
488
+            ->setValue('password', $qb->createNamedParameter($password))
489
+            ->setValue('stime', $qb->createNamedParameter(time()));
490
+
491
+        /*
492 492
 		 * Added to fix https://github.com/owncloud/core/issues/22215
493 493
 		 * Can be removed once we get rid of ajax/share.php
494 494
 		 */
495
-		$qb->setValue('file_target', $qb->createNamedParameter(''));
495
+        $qb->setValue('file_target', $qb->createNamedParameter(''));
496 496
 
497
-		$qb->execute();
498
-		$id = $qb->getLastInsertId();
497
+        $qb->execute();
498
+        $id = $qb->getLastInsertId();
499 499
 
500
-		return (int)$id;
501
-	}
500
+        return (int)$id;
501
+    }
502 502
 
503
-	/**
504
-	 * Update a share
505
-	 *
506
-	 * @param IShare $share
507
-	 * @param string|null $plainTextPassword
508
-	 * @return IShare The share object
509
-	 */
510
-	public function update(IShare $share, $plainTextPassword = null) {
503
+    /**
504
+     * Update a share
505
+     *
506
+     * @param IShare $share
507
+     * @param string|null $plainTextPassword
508
+     * @return IShare The share object
509
+     */
510
+    public function update(IShare $share, $plainTextPassword = null) {
511 511
 
512
-		$originalShare = $this->getShareById($share->getId());
512
+        $originalShare = $this->getShareById($share->getId());
513 513
 
514
-		// a real password was given
515
-		$validPassword = $plainTextPassword !== null && $plainTextPassword !== '';
514
+        // a real password was given
515
+        $validPassword = $plainTextPassword !== null && $plainTextPassword !== '';
516 516
 
517
-		if($validPassword && $originalShare->getPassword() !== $share->getPassword()) {
518
-			$this->sendPassword($share->getNode()->getName(), $share->getSharedBy(), $share->getSharedWith(), $plainTextPassword);
519
-		}
520
-		/*
517
+        if($validPassword && $originalShare->getPassword() !== $share->getPassword()) {
518
+            $this->sendPassword($share->getNode()->getName(), $share->getSharedBy(), $share->getSharedWith(), $plainTextPassword);
519
+        }
520
+        /*
521 521
 		 * We allow updating the permissions and password of mail shares
522 522
 		 */
523
-		$qb = $this->dbConnection->getQueryBuilder();
524
-		$qb->update('share')
525
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
526
-			->set('permissions', $qb->createNamedParameter($share->getPermissions()))
527
-			->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
528
-			->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
529
-			->set('password', $qb->createNamedParameter($share->getPassword()))
530
-			->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
531
-			->execute();
532
-
533
-		return $share;
534
-	}
535
-
536
-	/**
537
-	 * @inheritdoc
538
-	 */
539
-	public function move(IShare $share, $recipient) {
540
-		/**
541
-		 * nothing to do here, mail shares are only outgoing shares
542
-		 */
543
-		return $share;
544
-	}
545
-
546
-	/**
547
-	 * Delete a share (owner unShares the file)
548
-	 *
549
-	 * @param IShare $share
550
-	 */
551
-	public function delete(IShare $share) {
552
-		$this->removeShareFromTable($share->getId());
553
-	}
554
-
555
-	/**
556
-	 * @inheritdoc
557
-	 */
558
-	public function deleteFromSelf(IShare $share, $recipient) {
559
-		// nothing to do here, mail shares are only outgoing shares
560
-		return;
561
-	}
562
-
563
-	/**
564
-	 * @inheritdoc
565
-	 */
566
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
567
-		$qb = $this->dbConnection->getQueryBuilder();
568
-		$qb->select('*')
569
-			->from('share');
570
-
571
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
572
-
573
-		/**
574
-		 * Reshares for this user are shares where they are the owner.
575
-		 */
576
-		if ($reshares === false) {
577
-			//Special case for old shares created via the web UI
578
-			$or1 = $qb->expr()->andX(
579
-				$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
580
-				$qb->expr()->isNull('uid_initiator')
581
-			);
582
-
583
-			$qb->andWhere(
584
-				$qb->expr()->orX(
585
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
586
-					$or1
587
-				)
588
-			);
589
-		} else {
590
-			$qb->andWhere(
591
-				$qb->expr()->orX(
592
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
593
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
594
-				)
595
-			);
596
-		}
597
-
598
-		if ($node !== null) {
599
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
600
-		}
601
-
602
-		if ($limit !== -1) {
603
-			$qb->setMaxResults($limit);
604
-		}
605
-
606
-		$qb->setFirstResult($offset);
607
-		$qb->orderBy('id');
608
-
609
-		$cursor = $qb->execute();
610
-		$shares = [];
611
-		while($data = $cursor->fetch()) {
612
-			$shares[] = $this->createShareObject($data);
613
-		}
614
-		$cursor->closeCursor();
615
-
616
-		return $shares;
617
-	}
618
-
619
-	/**
620
-	 * @inheritdoc
621
-	 */
622
-	public function getShareById($id, $recipientId = null) {
623
-		$qb = $this->dbConnection->getQueryBuilder();
624
-
625
-		$qb->select('*')
626
-			->from('share')
627
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
628
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
629
-
630
-		$cursor = $qb->execute();
631
-		$data = $cursor->fetch();
632
-		$cursor->closeCursor();
633
-
634
-		if ($data === false) {
635
-			throw new ShareNotFound();
636
-		}
637
-
638
-		try {
639
-			$share = $this->createShareObject($data);
640
-		} catch (InvalidShare $e) {
641
-			throw new ShareNotFound();
642
-		}
643
-
644
-		return $share;
645
-	}
646
-
647
-	/**
648
-	 * Get shares for a given path
649
-	 *
650
-	 * @param \OCP\Files\Node $path
651
-	 * @return IShare[]
652
-	 */
653
-	public function getSharesByPath(Node $path) {
654
-		$qb = $this->dbConnection->getQueryBuilder();
655
-
656
-		$cursor = $qb->select('*')
657
-			->from('share')
658
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
659
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
660
-			->execute();
661
-
662
-		$shares = [];
663
-		while($data = $cursor->fetch()) {
664
-			$shares[] = $this->createShareObject($data);
665
-		}
666
-		$cursor->closeCursor();
667
-
668
-		return $shares;
669
-	}
670
-
671
-	/**
672
-	 * @inheritdoc
673
-	 */
674
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
675
-		/** @var IShare[] $shares */
676
-		$shares = [];
677
-
678
-		//Get shares directly with this user
679
-		$qb = $this->dbConnection->getQueryBuilder();
680
-		$qb->select('*')
681
-			->from('share');
682
-
683
-		// Order by id
684
-		$qb->orderBy('id');
685
-
686
-		// Set limit and offset
687
-		if ($limit !== -1) {
688
-			$qb->setMaxResults($limit);
689
-		}
690
-		$qb->setFirstResult($offset);
691
-
692
-		$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
693
-		$qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
694
-
695
-		// Filter by node if provided
696
-		if ($node !== null) {
697
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
698
-		}
699
-
700
-		$cursor = $qb->execute();
701
-
702
-		while($data = $cursor->fetch()) {
703
-			$shares[] = $this->createShareObject($data);
704
-		}
705
-		$cursor->closeCursor();
706
-
707
-
708
-		return $shares;
709
-	}
710
-
711
-	/**
712
-	 * Get a share by token
713
-	 *
714
-	 * @param string $token
715
-	 * @return IShare
716
-	 * @throws ShareNotFound
717
-	 */
718
-	public function getShareByToken($token) {
719
-		$qb = $this->dbConnection->getQueryBuilder();
720
-
721
-		$cursor = $qb->select('*')
722
-			->from('share')
723
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
724
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
725
-			->execute();
726
-
727
-		$data = $cursor->fetch();
728
-
729
-		if ($data === false) {
730
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
731
-		}
732
-
733
-		try {
734
-			$share = $this->createShareObject($data);
735
-		} catch (InvalidShare $e) {
736
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
737
-		}
738
-
739
-		return $share;
740
-	}
741
-
742
-	/**
743
-	 * remove share from table
744
-	 *
745
-	 * @param string $shareId
746
-	 */
747
-	protected function removeShareFromTable($shareId) {
748
-		$qb = $this->dbConnection->getQueryBuilder();
749
-		$qb->delete('share')
750
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
751
-		$qb->execute();
752
-	}
753
-
754
-	/**
755
-	 * Create a share object from an database row
756
-	 *
757
-	 * @param array $data
758
-	 * @return IShare
759
-	 * @throws InvalidShare
760
-	 * @throws ShareNotFound
761
-	 */
762
-	protected function createShareObject($data) {
763
-
764
-		$share = new Share($this->rootFolder, $this->userManager);
765
-		$share->setId((int)$data['id'])
766
-			->setShareType((int)$data['share_type'])
767
-			->setPermissions((int)$data['permissions'])
768
-			->setTarget($data['file_target'])
769
-			->setMailSend((bool)$data['mail_send'])
770
-			->setToken($data['token']);
771
-
772
-		$shareTime = new \DateTime();
773
-		$shareTime->setTimestamp((int)$data['stime']);
774
-		$share->setShareTime($shareTime);
775
-		$share->setSharedWith($data['share_with']);
776
-		$share->setPassword($data['password']);
777
-
778
-		if ($data['uid_initiator'] !== null) {
779
-			$share->setShareOwner($data['uid_owner']);
780
-			$share->setSharedBy($data['uid_initiator']);
781
-		} else {
782
-			//OLD SHARE
783
-			$share->setSharedBy($data['uid_owner']);
784
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
785
-
786
-			$owner = $path->getOwner();
787
-			$share->setShareOwner($owner->getUID());
788
-		}
789
-
790
-		if ($data['expiration'] !== null) {
791
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
792
-			if ($expiration !== false) {
793
-				$share->setExpirationDate($expiration);
794
-			}
795
-		}
796
-
797
-		$share->setNodeId((int)$data['file_source']);
798
-		$share->setNodeType($data['item_type']);
799
-
800
-		$share->setProviderId($this->identifier());
801
-
802
-		return $share;
803
-	}
804
-
805
-	/**
806
-	 * Get the node with file $id for $user
807
-	 *
808
-	 * @param string $userId
809
-	 * @param int $id
810
-	 * @return \OCP\Files\File|\OCP\Files\Folder
811
-	 * @throws InvalidShare
812
-	 */
813
-	private function getNode($userId, $id) {
814
-		try {
815
-			$userFolder = $this->rootFolder->getUserFolder($userId);
816
-		} catch (NotFoundException $e) {
817
-			throw new InvalidShare();
818
-		}
819
-
820
-		$nodes = $userFolder->getById($id);
821
-
822
-		if (empty($nodes)) {
823
-			throw new InvalidShare();
824
-		}
825
-
826
-		return $nodes[0];
827
-	}
828
-
829
-	/**
830
-	 * A user is deleted from the system
831
-	 * So clean up the relevant shares.
832
-	 *
833
-	 * @param string $uid
834
-	 * @param int $shareType
835
-	 */
836
-	public function userDeleted($uid, $shareType) {
837
-		$qb = $this->dbConnection->getQueryBuilder();
838
-
839
-		$qb->delete('share')
840
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
841
-			->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
842
-			->execute();
843
-	}
844
-
845
-	/**
846
-	 * This provider does not support group shares
847
-	 *
848
-	 * @param string $gid
849
-	 */
850
-	public function groupDeleted($gid) {
851
-		return;
852
-	}
853
-
854
-	/**
855
-	 * This provider does not support group shares
856
-	 *
857
-	 * @param string $uid
858
-	 * @param string $gid
859
-	 */
860
-	public function userDeletedFromGroup($uid, $gid) {
861
-		return;
862
-	}
863
-
864
-	/**
865
-	 * get database row of a give share
866
-	 *
867
-	 * @param $id
868
-	 * @return array
869
-	 * @throws ShareNotFound
870
-	 */
871
-	protected function getRawShare($id) {
872
-
873
-		// Now fetch the inserted share and create a complete share object
874
-		$qb = $this->dbConnection->getQueryBuilder();
875
-		$qb->select('*')
876
-			->from('share')
877
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
878
-
879
-		$cursor = $qb->execute();
880
-		$data = $cursor->fetch();
881
-		$cursor->closeCursor();
882
-
883
-		if ($data === false) {
884
-			throw new ShareNotFound;
885
-		}
886
-
887
-		return $data;
888
-	}
889
-
890
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
891
-		$qb = $this->dbConnection->getQueryBuilder();
892
-		$qb->select('*')
893
-			->from('share', 's')
894
-			->andWhere($qb->expr()->orX(
895
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
896
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
897
-			))
898
-			->andWhere(
899
-				$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
900
-			);
901
-
902
-		/**
903
-		 * Reshares for this user are shares where they are the owner.
904
-		 */
905
-		if ($reshares === false) {
906
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
907
-		} else {
908
-			$qb->andWhere(
909
-				$qb->expr()->orX(
910
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
911
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
912
-				)
913
-			);
914
-		}
915
-
916
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
917
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
918
-
919
-		$qb->orderBy('id');
920
-
921
-		$cursor = $qb->execute();
922
-		$shares = [];
923
-		while ($data = $cursor->fetch()) {
924
-			$shares[$data['fileid']][] = $this->createShareObject($data);
925
-		}
926
-		$cursor->closeCursor();
927
-
928
-		return $shares;
929
-	}
523
+        $qb = $this->dbConnection->getQueryBuilder();
524
+        $qb->update('share')
525
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
526
+            ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
527
+            ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
528
+            ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
529
+            ->set('password', $qb->createNamedParameter($share->getPassword()))
530
+            ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
531
+            ->execute();
532
+
533
+        return $share;
534
+    }
535
+
536
+    /**
537
+     * @inheritdoc
538
+     */
539
+    public function move(IShare $share, $recipient) {
540
+        /**
541
+         * nothing to do here, mail shares are only outgoing shares
542
+         */
543
+        return $share;
544
+    }
545
+
546
+    /**
547
+     * Delete a share (owner unShares the file)
548
+     *
549
+     * @param IShare $share
550
+     */
551
+    public function delete(IShare $share) {
552
+        $this->removeShareFromTable($share->getId());
553
+    }
554
+
555
+    /**
556
+     * @inheritdoc
557
+     */
558
+    public function deleteFromSelf(IShare $share, $recipient) {
559
+        // nothing to do here, mail shares are only outgoing shares
560
+        return;
561
+    }
562
+
563
+    /**
564
+     * @inheritdoc
565
+     */
566
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
567
+        $qb = $this->dbConnection->getQueryBuilder();
568
+        $qb->select('*')
569
+            ->from('share');
570
+
571
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
572
+
573
+        /**
574
+         * Reshares for this user are shares where they are the owner.
575
+         */
576
+        if ($reshares === false) {
577
+            //Special case for old shares created via the web UI
578
+            $or1 = $qb->expr()->andX(
579
+                $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
580
+                $qb->expr()->isNull('uid_initiator')
581
+            );
582
+
583
+            $qb->andWhere(
584
+                $qb->expr()->orX(
585
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
586
+                    $or1
587
+                )
588
+            );
589
+        } else {
590
+            $qb->andWhere(
591
+                $qb->expr()->orX(
592
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
593
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
594
+                )
595
+            );
596
+        }
597
+
598
+        if ($node !== null) {
599
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
600
+        }
601
+
602
+        if ($limit !== -1) {
603
+            $qb->setMaxResults($limit);
604
+        }
605
+
606
+        $qb->setFirstResult($offset);
607
+        $qb->orderBy('id');
608
+
609
+        $cursor = $qb->execute();
610
+        $shares = [];
611
+        while($data = $cursor->fetch()) {
612
+            $shares[] = $this->createShareObject($data);
613
+        }
614
+        $cursor->closeCursor();
615
+
616
+        return $shares;
617
+    }
618
+
619
+    /**
620
+     * @inheritdoc
621
+     */
622
+    public function getShareById($id, $recipientId = null) {
623
+        $qb = $this->dbConnection->getQueryBuilder();
624
+
625
+        $qb->select('*')
626
+            ->from('share')
627
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
628
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
629
+
630
+        $cursor = $qb->execute();
631
+        $data = $cursor->fetch();
632
+        $cursor->closeCursor();
633
+
634
+        if ($data === false) {
635
+            throw new ShareNotFound();
636
+        }
637
+
638
+        try {
639
+            $share = $this->createShareObject($data);
640
+        } catch (InvalidShare $e) {
641
+            throw new ShareNotFound();
642
+        }
643
+
644
+        return $share;
645
+    }
646
+
647
+    /**
648
+     * Get shares for a given path
649
+     *
650
+     * @param \OCP\Files\Node $path
651
+     * @return IShare[]
652
+     */
653
+    public function getSharesByPath(Node $path) {
654
+        $qb = $this->dbConnection->getQueryBuilder();
655
+
656
+        $cursor = $qb->select('*')
657
+            ->from('share')
658
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
659
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
660
+            ->execute();
661
+
662
+        $shares = [];
663
+        while($data = $cursor->fetch()) {
664
+            $shares[] = $this->createShareObject($data);
665
+        }
666
+        $cursor->closeCursor();
667
+
668
+        return $shares;
669
+    }
670
+
671
+    /**
672
+     * @inheritdoc
673
+     */
674
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
675
+        /** @var IShare[] $shares */
676
+        $shares = [];
677
+
678
+        //Get shares directly with this user
679
+        $qb = $this->dbConnection->getQueryBuilder();
680
+        $qb->select('*')
681
+            ->from('share');
682
+
683
+        // Order by id
684
+        $qb->orderBy('id');
685
+
686
+        // Set limit and offset
687
+        if ($limit !== -1) {
688
+            $qb->setMaxResults($limit);
689
+        }
690
+        $qb->setFirstResult($offset);
691
+
692
+        $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
693
+        $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
694
+
695
+        // Filter by node if provided
696
+        if ($node !== null) {
697
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
698
+        }
699
+
700
+        $cursor = $qb->execute();
701
+
702
+        while($data = $cursor->fetch()) {
703
+            $shares[] = $this->createShareObject($data);
704
+        }
705
+        $cursor->closeCursor();
706
+
707
+
708
+        return $shares;
709
+    }
710
+
711
+    /**
712
+     * Get a share by token
713
+     *
714
+     * @param string $token
715
+     * @return IShare
716
+     * @throws ShareNotFound
717
+     */
718
+    public function getShareByToken($token) {
719
+        $qb = $this->dbConnection->getQueryBuilder();
720
+
721
+        $cursor = $qb->select('*')
722
+            ->from('share')
723
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
724
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
725
+            ->execute();
726
+
727
+        $data = $cursor->fetch();
728
+
729
+        if ($data === false) {
730
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
731
+        }
732
+
733
+        try {
734
+            $share = $this->createShareObject($data);
735
+        } catch (InvalidShare $e) {
736
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
737
+        }
738
+
739
+        return $share;
740
+    }
741
+
742
+    /**
743
+     * remove share from table
744
+     *
745
+     * @param string $shareId
746
+     */
747
+    protected function removeShareFromTable($shareId) {
748
+        $qb = $this->dbConnection->getQueryBuilder();
749
+        $qb->delete('share')
750
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
751
+        $qb->execute();
752
+    }
753
+
754
+    /**
755
+     * Create a share object from an database row
756
+     *
757
+     * @param array $data
758
+     * @return IShare
759
+     * @throws InvalidShare
760
+     * @throws ShareNotFound
761
+     */
762
+    protected function createShareObject($data) {
763
+
764
+        $share = new Share($this->rootFolder, $this->userManager);
765
+        $share->setId((int)$data['id'])
766
+            ->setShareType((int)$data['share_type'])
767
+            ->setPermissions((int)$data['permissions'])
768
+            ->setTarget($data['file_target'])
769
+            ->setMailSend((bool)$data['mail_send'])
770
+            ->setToken($data['token']);
771
+
772
+        $shareTime = new \DateTime();
773
+        $shareTime->setTimestamp((int)$data['stime']);
774
+        $share->setShareTime($shareTime);
775
+        $share->setSharedWith($data['share_with']);
776
+        $share->setPassword($data['password']);
777
+
778
+        if ($data['uid_initiator'] !== null) {
779
+            $share->setShareOwner($data['uid_owner']);
780
+            $share->setSharedBy($data['uid_initiator']);
781
+        } else {
782
+            //OLD SHARE
783
+            $share->setSharedBy($data['uid_owner']);
784
+            $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
785
+
786
+            $owner = $path->getOwner();
787
+            $share->setShareOwner($owner->getUID());
788
+        }
789
+
790
+        if ($data['expiration'] !== null) {
791
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
792
+            if ($expiration !== false) {
793
+                $share->setExpirationDate($expiration);
794
+            }
795
+        }
796
+
797
+        $share->setNodeId((int)$data['file_source']);
798
+        $share->setNodeType($data['item_type']);
799
+
800
+        $share->setProviderId($this->identifier());
801
+
802
+        return $share;
803
+    }
804
+
805
+    /**
806
+     * Get the node with file $id for $user
807
+     *
808
+     * @param string $userId
809
+     * @param int $id
810
+     * @return \OCP\Files\File|\OCP\Files\Folder
811
+     * @throws InvalidShare
812
+     */
813
+    private function getNode($userId, $id) {
814
+        try {
815
+            $userFolder = $this->rootFolder->getUserFolder($userId);
816
+        } catch (NotFoundException $e) {
817
+            throw new InvalidShare();
818
+        }
819
+
820
+        $nodes = $userFolder->getById($id);
821
+
822
+        if (empty($nodes)) {
823
+            throw new InvalidShare();
824
+        }
825
+
826
+        return $nodes[0];
827
+    }
828
+
829
+    /**
830
+     * A user is deleted from the system
831
+     * So clean up the relevant shares.
832
+     *
833
+     * @param string $uid
834
+     * @param int $shareType
835
+     */
836
+    public function userDeleted($uid, $shareType) {
837
+        $qb = $this->dbConnection->getQueryBuilder();
838
+
839
+        $qb->delete('share')
840
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
841
+            ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
842
+            ->execute();
843
+    }
844
+
845
+    /**
846
+     * This provider does not support group shares
847
+     *
848
+     * @param string $gid
849
+     */
850
+    public function groupDeleted($gid) {
851
+        return;
852
+    }
853
+
854
+    /**
855
+     * This provider does not support group shares
856
+     *
857
+     * @param string $uid
858
+     * @param string $gid
859
+     */
860
+    public function userDeletedFromGroup($uid, $gid) {
861
+        return;
862
+    }
863
+
864
+    /**
865
+     * get database row of a give share
866
+     *
867
+     * @param $id
868
+     * @return array
869
+     * @throws ShareNotFound
870
+     */
871
+    protected function getRawShare($id) {
872
+
873
+        // Now fetch the inserted share and create a complete share object
874
+        $qb = $this->dbConnection->getQueryBuilder();
875
+        $qb->select('*')
876
+            ->from('share')
877
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
878
+
879
+        $cursor = $qb->execute();
880
+        $data = $cursor->fetch();
881
+        $cursor->closeCursor();
882
+
883
+        if ($data === false) {
884
+            throw new ShareNotFound;
885
+        }
886
+
887
+        return $data;
888
+    }
889
+
890
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
891
+        $qb = $this->dbConnection->getQueryBuilder();
892
+        $qb->select('*')
893
+            ->from('share', 's')
894
+            ->andWhere($qb->expr()->orX(
895
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
896
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
897
+            ))
898
+            ->andWhere(
899
+                $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
900
+            );
901
+
902
+        /**
903
+         * Reshares for this user are shares where they are the owner.
904
+         */
905
+        if ($reshares === false) {
906
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
907
+        } else {
908
+            $qb->andWhere(
909
+                $qb->expr()->orX(
910
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
911
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
912
+                )
913
+            );
914
+        }
915
+
916
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
917
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
918
+
919
+        $qb->orderBy('id');
920
+
921
+        $cursor = $qb->execute();
922
+        $shares = [];
923
+        while ($data = $cursor->fetch()) {
924
+            $shares[$data['fileid']][] = $this->createShareObject($data);
925
+        }
926
+        $cursor->closeCursor();
927
+
928
+        return $shares;
929
+    }
930 930
 
931 931
 }
Please login to merge, or discard this patch.
lib/private/Share20/ProviderFactory.php 1 patch
Indentation   +211 added lines, -211 removed lines patch added patch discarded remove patch
@@ -41,222 +41,222 @@
 block discarded – undo
41 41
  */
42 42
 class ProviderFactory implements IProviderFactory {
43 43
 
44
-	/** @var IServerContainer */
45
-	private $serverContainer;
46
-	/** @var DefaultShareProvider */
47
-	private $defaultProvider = null;
48
-	/** @var FederatedShareProvider */
49
-	private $federatedProvider = null;
50
-	/** @var  ShareByMailProvider */
51
-	private $shareByMailProvider;
52
-	/** @var  \OCA\Circles\ShareByCircleProvider;
53
-	 * ShareByCircleProvider */
54
-	private $shareByCircleProvider;
55
-
56
-	/**
57
-	 * IProviderFactory constructor.
58
-	 *
59
-	 * @param IServerContainer $serverContainer
60
-	 */
61
-	public function __construct(IServerContainer $serverContainer) {
62
-		$this->serverContainer = $serverContainer;
63
-	}
64
-
65
-	/**
66
-	 * Create the default share provider.
67
-	 *
68
-	 * @return DefaultShareProvider
69
-	 */
70
-	protected function defaultShareProvider() {
71
-		if ($this->defaultProvider === null) {
72
-			$this->defaultProvider = new DefaultShareProvider(
73
-				$this->serverContainer->getDatabaseConnection(),
74
-				$this->serverContainer->getUserManager(),
75
-				$this->serverContainer->getGroupManager(),
76
-				$this->serverContainer->getLazyRootFolder()
77
-			);
78
-		}
79
-
80
-		return $this->defaultProvider;
81
-	}
82
-
83
-	/**
84
-	 * Create the federated share provider
85
-	 *
86
-	 * @return FederatedShareProvider
87
-	 */
88
-	protected function federatedShareProvider() {
89
-		if ($this->federatedProvider === null) {
90
-			/*
44
+    /** @var IServerContainer */
45
+    private $serverContainer;
46
+    /** @var DefaultShareProvider */
47
+    private $defaultProvider = null;
48
+    /** @var FederatedShareProvider */
49
+    private $federatedProvider = null;
50
+    /** @var  ShareByMailProvider */
51
+    private $shareByMailProvider;
52
+    /** @var  \OCA\Circles\ShareByCircleProvider;
53
+     * ShareByCircleProvider */
54
+    private $shareByCircleProvider;
55
+
56
+    /**
57
+     * IProviderFactory constructor.
58
+     *
59
+     * @param IServerContainer $serverContainer
60
+     */
61
+    public function __construct(IServerContainer $serverContainer) {
62
+        $this->serverContainer = $serverContainer;
63
+    }
64
+
65
+    /**
66
+     * Create the default share provider.
67
+     *
68
+     * @return DefaultShareProvider
69
+     */
70
+    protected function defaultShareProvider() {
71
+        if ($this->defaultProvider === null) {
72
+            $this->defaultProvider = new DefaultShareProvider(
73
+                $this->serverContainer->getDatabaseConnection(),
74
+                $this->serverContainer->getUserManager(),
75
+                $this->serverContainer->getGroupManager(),
76
+                $this->serverContainer->getLazyRootFolder()
77
+            );
78
+        }
79
+
80
+        return $this->defaultProvider;
81
+    }
82
+
83
+    /**
84
+     * Create the federated share provider
85
+     *
86
+     * @return FederatedShareProvider
87
+     */
88
+    protected function federatedShareProvider() {
89
+        if ($this->federatedProvider === null) {
90
+            /*
91 91
 			 * Check if the app is enabled
92 92
 			 */
93
-			$appManager = $this->serverContainer->getAppManager();
94
-			if (!$appManager->isEnabledForUser('federatedfilesharing')) {
95
-				return null;
96
-			}
93
+            $appManager = $this->serverContainer->getAppManager();
94
+            if (!$appManager->isEnabledForUser('federatedfilesharing')) {
95
+                return null;
96
+            }
97 97
 
98
-			/*
98
+            /*
99 99
 			 * TODO: add factory to federated sharing app
100 100
 			 */
101
-			$l = $this->serverContainer->getL10N('federatedfilessharing');
102
-			$addressHandler = new AddressHandler(
103
-				$this->serverContainer->getURLGenerator(),
104
-				$l,
105
-				$this->serverContainer->getCloudIdManager()
106
-			);
107
-			$notifications = new Notifications(
108
-				$addressHandler,
109
-				$this->serverContainer->getHTTPClientService(),
110
-				$this->serverContainer->query(\OCP\OCS\IDiscoveryService::class),
111
-				$this->serverContainer->getJobList()
112
-			);
113
-			$tokenHandler = new TokenHandler(
114
-				$this->serverContainer->getSecureRandom()
115
-			);
116
-
117
-			$this->federatedProvider = new FederatedShareProvider(
118
-				$this->serverContainer->getDatabaseConnection(),
119
-				$addressHandler,
120
-				$notifications,
121
-				$tokenHandler,
122
-				$l,
123
-				$this->serverContainer->getLogger(),
124
-				$this->serverContainer->getLazyRootFolder(),
125
-				$this->serverContainer->getConfig(),
126
-				$this->serverContainer->getUserManager(),
127
-				$this->serverContainer->getCloudIdManager()
128
-			);
129
-		}
130
-
131
-		return $this->federatedProvider;
132
-	}
133
-
134
-	/**
135
-	 * Create the federated share provider
136
-	 *
137
-	 * @return ShareByMailProvider
138
-	 */
139
-	protected function getShareByMailProvider() {
140
-		if ($this->shareByMailProvider === null) {
141
-			/*
101
+            $l = $this->serverContainer->getL10N('federatedfilessharing');
102
+            $addressHandler = new AddressHandler(
103
+                $this->serverContainer->getURLGenerator(),
104
+                $l,
105
+                $this->serverContainer->getCloudIdManager()
106
+            );
107
+            $notifications = new Notifications(
108
+                $addressHandler,
109
+                $this->serverContainer->getHTTPClientService(),
110
+                $this->serverContainer->query(\OCP\OCS\IDiscoveryService::class),
111
+                $this->serverContainer->getJobList()
112
+            );
113
+            $tokenHandler = new TokenHandler(
114
+                $this->serverContainer->getSecureRandom()
115
+            );
116
+
117
+            $this->federatedProvider = new FederatedShareProvider(
118
+                $this->serverContainer->getDatabaseConnection(),
119
+                $addressHandler,
120
+                $notifications,
121
+                $tokenHandler,
122
+                $l,
123
+                $this->serverContainer->getLogger(),
124
+                $this->serverContainer->getLazyRootFolder(),
125
+                $this->serverContainer->getConfig(),
126
+                $this->serverContainer->getUserManager(),
127
+                $this->serverContainer->getCloudIdManager()
128
+            );
129
+        }
130
+
131
+        return $this->federatedProvider;
132
+    }
133
+
134
+    /**
135
+     * Create the federated share provider
136
+     *
137
+     * @return ShareByMailProvider
138
+     */
139
+    protected function getShareByMailProvider() {
140
+        if ($this->shareByMailProvider === null) {
141
+            /*
142 142
 			 * Check if the app is enabled
143 143
 			 */
144
-			$appManager = $this->serverContainer->getAppManager();
145
-			if (!$appManager->isEnabledForUser('sharebymail')) {
146
-				return null;
147
-			}
148
-
149
-			$settingsManager = new SettingsManager($this->serverContainer->getConfig());
150
-
151
-			$this->shareByMailProvider = new ShareByMailProvider(
152
-				$this->serverContainer->getDatabaseConnection(),
153
-				$this->serverContainer->getSecureRandom(),
154
-				$this->serverContainer->getUserManager(),
155
-				$this->serverContainer->getLazyRootFolder(),
156
-				$this->serverContainer->getL10N('sharebymail'),
157
-				$this->serverContainer->getLogger(),
158
-				$this->serverContainer->getMailer(),
159
-				$this->serverContainer->getURLGenerator(),
160
-				$this->serverContainer->getActivityManager(),
161
-				$settingsManager,
162
-				$this->serverContainer->getHasher()
163
-			);
164
-		}
165
-
166
-		return $this->shareByMailProvider;
167
-	}
168
-
169
-
170
-	/**
171
-	 * Create the circle share provider
172
-	 *
173
-	 * @return FederatedShareProvider
174
-	 */
175
-	protected function getShareByCircleProvider() {
176
-
177
-		$appManager = $this->serverContainer->getAppManager();
178
-		if (!$appManager->isEnabledForUser('circles')) {
179
-			return null;
180
-		}
181
-
182
-
183
-		if ($this->shareByCircleProvider === null) {
184
-
185
-			$this->shareByCircleProvider = new \OCA\Circles\ShareByCircleProvider(
186
-				$this->serverContainer->getDatabaseConnection(),
187
-				$this->serverContainer->getSecureRandom(),
188
-				$this->serverContainer->getUserManager(),
189
-				$this->serverContainer->getLazyRootFolder(),
190
-				$this->serverContainer->getL10N('circles'),
191
-				$this->serverContainer->getLogger(),
192
-				$this->serverContainer->getURLGenerator()
193
-			);
194
-		}
195
-
196
-		return $this->shareByCircleProvider;
197
-	}
198
-
199
-
200
-	/**
201
-	 * @inheritdoc
202
-	 */
203
-	public function getProvider($id) {
204
-		$provider = null;
205
-		if ($id === 'ocinternal') {
206
-			$provider = $this->defaultShareProvider();
207
-		} else if ($id === 'ocFederatedSharing') {
208
-			$provider = $this->federatedShareProvider();
209
-		} else if ($id === 'ocMailShare') {
210
-			$provider = $this->getShareByMailProvider();
211
-		} else if ($id === 'ocCircleShare') {
212
-			$provider = $this->getShareByCircleProvider();
213
-		}
214
-
215
-		if ($provider === null) {
216
-			throw new ProviderException('No provider with id .' . $id . ' found.');
217
-		}
218
-
219
-		return $provider;
220
-	}
221
-
222
-	/**
223
-	 * @inheritdoc
224
-	 */
225
-	public function getProviderForType($shareType) {
226
-		$provider = null;
227
-
228
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER ||
229
-			$shareType === \OCP\Share::SHARE_TYPE_GROUP ||
230
-			$shareType === \OCP\Share::SHARE_TYPE_LINK
231
-		) {
232
-			$provider = $this->defaultShareProvider();
233
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
234
-			$provider = $this->federatedShareProvider();
235
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
236
-			$provider = $this->getShareByMailProvider();
237
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
238
-			$provider = $this->getShareByCircleProvider();
239
-		}
240
-
241
-
242
-		if ($provider === null) {
243
-			throw new ProviderException('No share provider for share type ' . $shareType);
244
-		}
245
-
246
-		return $provider;
247
-	}
248
-
249
-	public function getAllProviders() {
250
-		$shares = [$this->defaultShareProvider(), $this->federatedShareProvider()];
251
-		$shareByMail = $this->getShareByMailProvider();
252
-		if ($shareByMail !== null) {
253
-			$shares[] = $shareByMail;
254
-		}
255
-		$shareByCircle = $this->getShareByCircleProvider();
256
-		if ($shareByCircle !== null) {
257
-			$shares[] = $shareByCircle;
258
-		}
259
-
260
-		return $shares;
261
-	}
144
+            $appManager = $this->serverContainer->getAppManager();
145
+            if (!$appManager->isEnabledForUser('sharebymail')) {
146
+                return null;
147
+            }
148
+
149
+            $settingsManager = new SettingsManager($this->serverContainer->getConfig());
150
+
151
+            $this->shareByMailProvider = new ShareByMailProvider(
152
+                $this->serverContainer->getDatabaseConnection(),
153
+                $this->serverContainer->getSecureRandom(),
154
+                $this->serverContainer->getUserManager(),
155
+                $this->serverContainer->getLazyRootFolder(),
156
+                $this->serverContainer->getL10N('sharebymail'),
157
+                $this->serverContainer->getLogger(),
158
+                $this->serverContainer->getMailer(),
159
+                $this->serverContainer->getURLGenerator(),
160
+                $this->serverContainer->getActivityManager(),
161
+                $settingsManager,
162
+                $this->serverContainer->getHasher()
163
+            );
164
+        }
165
+
166
+        return $this->shareByMailProvider;
167
+    }
168
+
169
+
170
+    /**
171
+     * Create the circle share provider
172
+     *
173
+     * @return FederatedShareProvider
174
+     */
175
+    protected function getShareByCircleProvider() {
176
+
177
+        $appManager = $this->serverContainer->getAppManager();
178
+        if (!$appManager->isEnabledForUser('circles')) {
179
+            return null;
180
+        }
181
+
182
+
183
+        if ($this->shareByCircleProvider === null) {
184
+
185
+            $this->shareByCircleProvider = new \OCA\Circles\ShareByCircleProvider(
186
+                $this->serverContainer->getDatabaseConnection(),
187
+                $this->serverContainer->getSecureRandom(),
188
+                $this->serverContainer->getUserManager(),
189
+                $this->serverContainer->getLazyRootFolder(),
190
+                $this->serverContainer->getL10N('circles'),
191
+                $this->serverContainer->getLogger(),
192
+                $this->serverContainer->getURLGenerator()
193
+            );
194
+        }
195
+
196
+        return $this->shareByCircleProvider;
197
+    }
198
+
199
+
200
+    /**
201
+     * @inheritdoc
202
+     */
203
+    public function getProvider($id) {
204
+        $provider = null;
205
+        if ($id === 'ocinternal') {
206
+            $provider = $this->defaultShareProvider();
207
+        } else if ($id === 'ocFederatedSharing') {
208
+            $provider = $this->federatedShareProvider();
209
+        } else if ($id === 'ocMailShare') {
210
+            $provider = $this->getShareByMailProvider();
211
+        } else if ($id === 'ocCircleShare') {
212
+            $provider = $this->getShareByCircleProvider();
213
+        }
214
+
215
+        if ($provider === null) {
216
+            throw new ProviderException('No provider with id .' . $id . ' found.');
217
+        }
218
+
219
+        return $provider;
220
+    }
221
+
222
+    /**
223
+     * @inheritdoc
224
+     */
225
+    public function getProviderForType($shareType) {
226
+        $provider = null;
227
+
228
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER ||
229
+            $shareType === \OCP\Share::SHARE_TYPE_GROUP ||
230
+            $shareType === \OCP\Share::SHARE_TYPE_LINK
231
+        ) {
232
+            $provider = $this->defaultShareProvider();
233
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
234
+            $provider = $this->federatedShareProvider();
235
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
236
+            $provider = $this->getShareByMailProvider();
237
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
238
+            $provider = $this->getShareByCircleProvider();
239
+        }
240
+
241
+
242
+        if ($provider === null) {
243
+            throw new ProviderException('No share provider for share type ' . $shareType);
244
+        }
245
+
246
+        return $provider;
247
+    }
248
+
249
+    public function getAllProviders() {
250
+        $shares = [$this->defaultShareProvider(), $this->federatedShareProvider()];
251
+        $shareByMail = $this->getShareByMailProvider();
252
+        if ($shareByMail !== null) {
253
+            $shares[] = $shareByMail;
254
+        }
255
+        $shareByCircle = $this->getShareByCircleProvider();
256
+        if ($shareByCircle !== null) {
257
+            $shares[] = $shareByCircle;
258
+        }
259
+
260
+        return $shares;
261
+    }
262 262
 }
Please login to merge, or discard this patch.