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