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