Completed
Push — master ( 01c9d0...055610 )
by Morris
02:24 queued 02:04
created
settings/Mailer/NewUserMailHelper.php 1 patch
Indentation   +123 added lines, -123 removed lines patch added patch discarded remove patch
@@ -34,133 +34,133 @@
 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 = new EMailTemplate(
119
-			$this->themingDefaults,
120
-			$this->urlGenerator,
121
-			$this->l10n
122
-		);
123
-		$emailTemplate->addHeader();
124
-		$displayName = $user->getDisplayName();
125
-		$userName = $user->getUID();
126
-		if ($displayName === $userName) {
127
-			$emailTemplate->addHeading($this->l10n->t('Welcome aboard'));
128
-		} else {
129
-			$emailTemplate->addHeading($this->l10n->t('Welcome aboard %s', [$displayName]));
130
-		}
131
-		$emailTemplate->addBodyText($this->l10n->t('You have now an %s account, you can add, protect, and share your data.', [$this->themingDefaults->getName()]));
132
-		$emailTemplate->addBodyText($this->l10n->t('Your username is: %s', [$userName]));
133
-		if ($generatePasswordResetToken) {
134
-			$leftButtonText = $this->l10n->t('Set your password');
135
-		} else {
136
-			$leftButtonText = $this->l10n->t('Go to %s', [$this->themingDefaults->getName()]);
137
-		}
138
-		$emailTemplate->addBodyButtonGroup(
139
-			$leftButtonText,
140
-			$link,
141
-			$this->l10n->t('Install Client'),
142
-			'https://nextcloud.com/install/#install-clients'
143
-		);
144
-		$emailTemplate->addFooter();
118
+        $emailTemplate = new EMailTemplate(
119
+            $this->themingDefaults,
120
+            $this->urlGenerator,
121
+            $this->l10n
122
+        );
123
+        $emailTemplate->addHeader();
124
+        $displayName = $user->getDisplayName();
125
+        $userName = $user->getUID();
126
+        if ($displayName === $userName) {
127
+            $emailTemplate->addHeading($this->l10n->t('Welcome aboard'));
128
+        } else {
129
+            $emailTemplate->addHeading($this->l10n->t('Welcome aboard %s', [$displayName]));
130
+        }
131
+        $emailTemplate->addBodyText($this->l10n->t('You have now an %s account, you can add, protect, and share your data.', [$this->themingDefaults->getName()]));
132
+        $emailTemplate->addBodyText($this->l10n->t('Your username is: %s', [$userName]));
133
+        if ($generatePasswordResetToken) {
134
+            $leftButtonText = $this->l10n->t('Set your password');
135
+        } else {
136
+            $leftButtonText = $this->l10n->t('Go to %s', [$this->themingDefaults->getName()]);
137
+        }
138
+        $emailTemplate->addBodyButtonGroup(
139
+            $leftButtonText,
140
+            $link,
141
+            $this->l10n->t('Install Client'),
142
+            'https://nextcloud.com/install/#install-clients'
143
+        );
144
+        $emailTemplate->addFooter();
145 145
 
146
-		return $emailTemplate;
147
-	}
146
+        return $emailTemplate;
147
+    }
148 148
 
149
-	/**
150
-	 * Sends a welcome mail to $user
151
-	 *
152
-	 * @param IUser $user
153
-	 * @param IEmailTemplate $emailTemplate
154
-	 * @throws \Exception If mail could not be sent
155
-	 */
156
-	public function sendMail(IUser $user,
157
-							 IEMailTemplate $emailTemplate) {
158
-		$message = $this->mailer->createMessage();
159
-		$message->setTo([$user->getEMailAddress() => $user->getDisplayName()]);
160
-		$message->setSubject($this->l10n->t('Your %s account was created', [$this->themingDefaults->getName()]));
161
-		$message->setHtmlBody($emailTemplate->renderHtml());
162
-		$message->setPlainBody($emailTemplate->renderText());
163
-		$message->setFrom([$this->fromAddress => $this->themingDefaults->getName()]);
164
-		$this->mailer->send($message);
165
-	}
149
+    /**
150
+     * Sends a welcome mail to $user
151
+     *
152
+     * @param IUser $user
153
+     * @param IEmailTemplate $emailTemplate
154
+     * @throws \Exception If mail could not be sent
155
+     */
156
+    public function sendMail(IUser $user,
157
+                                IEMailTemplate $emailTemplate) {
158
+        $message = $this->mailer->createMessage();
159
+        $message->setTo([$user->getEMailAddress() => $user->getDisplayName()]);
160
+        $message->setSubject($this->l10n->t('Your %s account was created', [$this->themingDefaults->getName()]));
161
+        $message->setHtmlBody($emailTemplate->renderHtml());
162
+        $message->setPlainBody($emailTemplate->renderText());
163
+        $message->setFrom([$this->fromAddress => $this->themingDefaults->getName()]);
164
+        $this->mailer->send($message);
165
+    }
166 166
 }
Please login to merge, or discard this patch.
settings/Hooks.php 1 patch
Indentation   +130 added lines, -130 removed lines patch added patch discarded remove patch
@@ -32,134 +32,134 @@
 block discarded – undo
32 32
 
33 33
 class Hooks {
34 34
 
35
-	/** @var IActivityManager */
36
-	protected $activityManager;
37
-	/** @var IUserManager */
38
-	protected $userManager;
39
-	/** @var IUserSession */
40
-	protected $userSession;
41
-	/** @var IURLGenerator */
42
-	protected $urlGenerator;
43
-	/** @var IMailer */
44
-	protected $mailer;
45
-	/** @var IL10N */
46
-	protected $l;
47
-
48
-	public function __construct(IActivityManager $activityManager, IUserManager $userManager, IUserSession $userSession, IURLGenerator $urlGenerator, IMailer $mailer, IL10N $l) {
49
-		$this->activityManager = $activityManager;
50
-		$this->userManager = $userManager;
51
-		$this->userSession = $userSession;
52
-		$this->urlGenerator = $urlGenerator;
53
-		$this->mailer = $mailer;
54
-		$this->l = $l;
55
-	}
56
-
57
-	/**
58
-	 * @param string $uid
59
-	 * @throws \InvalidArgumentException
60
-	 * @throws \BadMethodCallException
61
-	 * @throws \Exception
62
-	 */
63
-	public function onChangePassword($uid) {
64
-		$user = $this->userManager->get($uid);
65
-
66
-		if (!$user instanceof IUser || $user->getEMailAddress() === null) {
67
-			return;
68
-		}
69
-
70
-		$event = $this->activityManager->generateEvent();
71
-		$event->setApp('settings')
72
-			->setType('personal_settings')
73
-			->setAffectedUser($user->getUID());
74
-
75
-		$instanceUrl = $this->urlGenerator->getAbsoluteURL('/');
76
-
77
-		$actor = $this->userSession->getUser();
78
-		if ($actor instanceof IUser) {
79
-			if ($actor->getUID() !== $user->getUID()) {
80
-				$text = $this->l->t('%1$s changed your password on %2$s.', [$actor->getDisplayName(), $instanceUrl]);
81
-				$event->setAuthor($actor->getUID())
82
-					->setSubject(Provider::PASSWORD_CHANGED_BY, [$actor->getUID()]);
83
-			} else {
84
-				$text = $this->l->t('Your password on %s was changed.', [$instanceUrl]);
85
-				$event->setAuthor($actor->getUID())
86
-					->setSubject(Provider::PASSWORD_CHANGED_SELF);
87
-			}
88
-		} else {
89
-			$text = $this->l->t('Your password on %s was reset by an administrator.', [$instanceUrl]);
90
-			$event->setSubject(Provider::PASSWORD_RESET);
91
-		}
92
-
93
-		$this->activityManager->publish($event);
94
-
95
-		if ($user->getEMailAddress() !== null) {
96
-			$template = $this->mailer->createEMailTemplate();
97
-			$template->addHeader();
98
-			$template->addHeading($this->l->t('Password changed for %s', $user->getDisplayName()), false);
99
-			$template->addBodyText($text . ' ' . $this->l->t('If you did not request this, please contact an administrator.'));
100
-			$template->addFooter();
101
-
102
-
103
-			$message = $this->mailer->createMessage();
104
-			$message->setTo([$user->getEMailAddress() => $user->getDisplayName()]);
105
-			$message->setSubject($this->l->t('Password for %1$s changed on %2$s', [$user->getDisplayName(), $instanceUrl]));
106
-			$message->setBody($template->renderText(), 'text/plain');
107
-			$message->setHtmlBody($template->renderHtml());
108
-
109
-			$this->mailer->send($message);
110
-		}
111
-	}
112
-
113
-	/**
114
-	 * @param IUser $user
115
-	 * @param string|null $oldMailAddress
116
-	 * @throws \InvalidArgumentException
117
-	 * @throws \BadMethodCallException
118
-	 */
119
-	public function onChangeEmail(IUser $user, $oldMailAddress) {
120
-		$event = $this->activityManager->generateEvent();
121
-		$event->setApp('settings')
122
-			->setType('personal_settings')
123
-			->setAffectedUser($user->getUID());
124
-
125
-		$instanceUrl = $this->urlGenerator->getAbsoluteURL('/');
126
-
127
-		$actor = $this->userSession->getUser();
128
-		if ($actor instanceof IUser) {
129
-			if ($actor->getUID() !== $user->getUID()) {
130
-				$text = $this->l->t('%1$s changed your email address on %2$s.', [$actor->getDisplayName(), $instanceUrl]);
131
-				$event->setAuthor($actor->getUID())
132
-					->setSubject(Provider::EMAIL_CHANGED_BY, [$actor->getUID()]);
133
-			} else {
134
-				$text = $this->l->t('Your email address on %s was changed.', [$instanceUrl]);
135
-				$event->setAuthor($actor->getUID())
136
-					->setSubject(Provider::EMAIL_CHANGED_SELF);
137
-			}
138
-		} else {
139
-			$text = $this->l->t('Your email address on %s was changed by an administrator.', [$instanceUrl]);
140
-			$event->setSubject(Provider::EMAIL_CHANGED);
141
-		}
142
-		$this->activityManager->publish($event);
143
-
144
-
145
-		if ($oldMailAddress !== null) {
146
-			$template = $this->mailer->createEMailTemplate();
147
-			$template->addHeader();
148
-			$template->addHeading($this->l->t('Email address changed for %s', $user->getDisplayName()), false);
149
-			$template->addBodyText($text . ' ' . $this->l->t('If you did not request this, please contact an administrator.'));
150
-			if ($user->getEMailAddress()) {
151
-				$template->addBodyText($this->l->t('The new email address is %s', $user->getEMailAddress()));
152
-			}
153
-			$template->addFooter();
154
-
155
-
156
-			$message = $this->mailer->createMessage();
157
-			$message->setTo([$oldMailAddress => $user->getDisplayName()]);
158
-			$message->setSubject($this->l->t('Email address for %1$s changed on %2$s', [$user->getDisplayName(), $instanceUrl]));
159
-			$message->setBody($template->renderText(), 'text/plain');
160
-			$message->setHtmlBody($template->renderHtml());
161
-
162
-			$this->mailer->send($message);
163
-		}
164
-	}
35
+    /** @var IActivityManager */
36
+    protected $activityManager;
37
+    /** @var IUserManager */
38
+    protected $userManager;
39
+    /** @var IUserSession */
40
+    protected $userSession;
41
+    /** @var IURLGenerator */
42
+    protected $urlGenerator;
43
+    /** @var IMailer */
44
+    protected $mailer;
45
+    /** @var IL10N */
46
+    protected $l;
47
+
48
+    public function __construct(IActivityManager $activityManager, IUserManager $userManager, IUserSession $userSession, IURLGenerator $urlGenerator, IMailer $mailer, IL10N $l) {
49
+        $this->activityManager = $activityManager;
50
+        $this->userManager = $userManager;
51
+        $this->userSession = $userSession;
52
+        $this->urlGenerator = $urlGenerator;
53
+        $this->mailer = $mailer;
54
+        $this->l = $l;
55
+    }
56
+
57
+    /**
58
+     * @param string $uid
59
+     * @throws \InvalidArgumentException
60
+     * @throws \BadMethodCallException
61
+     * @throws \Exception
62
+     */
63
+    public function onChangePassword($uid) {
64
+        $user = $this->userManager->get($uid);
65
+
66
+        if (!$user instanceof IUser || $user->getEMailAddress() === null) {
67
+            return;
68
+        }
69
+
70
+        $event = $this->activityManager->generateEvent();
71
+        $event->setApp('settings')
72
+            ->setType('personal_settings')
73
+            ->setAffectedUser($user->getUID());
74
+
75
+        $instanceUrl = $this->urlGenerator->getAbsoluteURL('/');
76
+
77
+        $actor = $this->userSession->getUser();
78
+        if ($actor instanceof IUser) {
79
+            if ($actor->getUID() !== $user->getUID()) {
80
+                $text = $this->l->t('%1$s changed your password on %2$s.', [$actor->getDisplayName(), $instanceUrl]);
81
+                $event->setAuthor($actor->getUID())
82
+                    ->setSubject(Provider::PASSWORD_CHANGED_BY, [$actor->getUID()]);
83
+            } else {
84
+                $text = $this->l->t('Your password on %s was changed.', [$instanceUrl]);
85
+                $event->setAuthor($actor->getUID())
86
+                    ->setSubject(Provider::PASSWORD_CHANGED_SELF);
87
+            }
88
+        } else {
89
+            $text = $this->l->t('Your password on %s was reset by an administrator.', [$instanceUrl]);
90
+            $event->setSubject(Provider::PASSWORD_RESET);
91
+        }
92
+
93
+        $this->activityManager->publish($event);
94
+
95
+        if ($user->getEMailAddress() !== null) {
96
+            $template = $this->mailer->createEMailTemplate();
97
+            $template->addHeader();
98
+            $template->addHeading($this->l->t('Password changed for %s', $user->getDisplayName()), false);
99
+            $template->addBodyText($text . ' ' . $this->l->t('If you did not request this, please contact an administrator.'));
100
+            $template->addFooter();
101
+
102
+
103
+            $message = $this->mailer->createMessage();
104
+            $message->setTo([$user->getEMailAddress() => $user->getDisplayName()]);
105
+            $message->setSubject($this->l->t('Password for %1$s changed on %2$s', [$user->getDisplayName(), $instanceUrl]));
106
+            $message->setBody($template->renderText(), 'text/plain');
107
+            $message->setHtmlBody($template->renderHtml());
108
+
109
+            $this->mailer->send($message);
110
+        }
111
+    }
112
+
113
+    /**
114
+     * @param IUser $user
115
+     * @param string|null $oldMailAddress
116
+     * @throws \InvalidArgumentException
117
+     * @throws \BadMethodCallException
118
+     */
119
+    public function onChangeEmail(IUser $user, $oldMailAddress) {
120
+        $event = $this->activityManager->generateEvent();
121
+        $event->setApp('settings')
122
+            ->setType('personal_settings')
123
+            ->setAffectedUser($user->getUID());
124
+
125
+        $instanceUrl = $this->urlGenerator->getAbsoluteURL('/');
126
+
127
+        $actor = $this->userSession->getUser();
128
+        if ($actor instanceof IUser) {
129
+            if ($actor->getUID() !== $user->getUID()) {
130
+                $text = $this->l->t('%1$s changed your email address on %2$s.', [$actor->getDisplayName(), $instanceUrl]);
131
+                $event->setAuthor($actor->getUID())
132
+                    ->setSubject(Provider::EMAIL_CHANGED_BY, [$actor->getUID()]);
133
+            } else {
134
+                $text = $this->l->t('Your email address on %s was changed.', [$instanceUrl]);
135
+                $event->setAuthor($actor->getUID())
136
+                    ->setSubject(Provider::EMAIL_CHANGED_SELF);
137
+            }
138
+        } else {
139
+            $text = $this->l->t('Your email address on %s was changed by an administrator.', [$instanceUrl]);
140
+            $event->setSubject(Provider::EMAIL_CHANGED);
141
+        }
142
+        $this->activityManager->publish($event);
143
+
144
+
145
+        if ($oldMailAddress !== null) {
146
+            $template = $this->mailer->createEMailTemplate();
147
+            $template->addHeader();
148
+            $template->addHeading($this->l->t('Email address changed for %s', $user->getDisplayName()), false);
149
+            $template->addBodyText($text . ' ' . $this->l->t('If you did not request this, please contact an administrator.'));
150
+            if ($user->getEMailAddress()) {
151
+                $template->addBodyText($this->l->t('The new email address is %s', $user->getEMailAddress()));
152
+            }
153
+            $template->addFooter();
154
+
155
+
156
+            $message = $this->mailer->createMessage();
157
+            $message->setTo([$oldMailAddress => $user->getDisplayName()]);
158
+            $message->setSubject($this->l->t('Email address for %1$s changed on %2$s', [$user->getDisplayName(), $instanceUrl]));
159
+            $message->setBody($template->renderText(), 'text/plain');
160
+            $message->setHtmlBody($template->renderHtml());
161
+
162
+            $this->mailer->send($message);
163
+        }
164
+    }
165 165
 }
Please login to merge, or discard this patch.
settings/Controller/MailSettingsController.php 1 patch
Indentation   +131 added lines, -131 removed lines patch added patch discarded remove patch
@@ -39,136 +39,136 @@
 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
-				$template->addHeader();
152
-				$template->addHeading($this->l10n->t('Well done, %s!', [$displayName]));
153
-				$template->addBodyText($this->l10n->t('If you received this email, the email configuration seems to be correct.'));
154
-				$template->addFooter();
155
-
156
-				$message = $this->mailer->createMessage();
157
-				$message->setTo([$email => $displayName]);
158
-				$message->setSubject($this->l10n->t('Email setting test'));
159
-				$message->setHtmlBody($template->renderHtml());
160
-				$message->setPlainBody($template->renderText());
161
-				$errors = $this->mailer->send($message);
162
-				if (!empty($errors)) {
163
-					throw new \RuntimeException($this->l10n->t('Mail could not be sent. Check your mail server log'));
164
-				}
165
-				return new DataResponse();
166
-			} catch (\Exception $e) {
167
-				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);
168
-			}
169
-		}
170
-
171
-		return new DataResponse($this->l10n->t('You need to set your user email before being able to send test emails.'), Http::STATUS_BAD_REQUEST);
172
-	}
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
+                $template->addHeader();
152
+                $template->addHeading($this->l10n->t('Well done, %s!', [$displayName]));
153
+                $template->addBodyText($this->l10n->t('If you received this email, the email configuration seems to be correct.'));
154
+                $template->addFooter();
155
+
156
+                $message = $this->mailer->createMessage();
157
+                $message->setTo([$email => $displayName]);
158
+                $message->setSubject($this->l10n->t('Email setting test'));
159
+                $message->setHtmlBody($template->renderHtml());
160
+                $message->setPlainBody($template->renderText());
161
+                $errors = $this->mailer->send($message);
162
+                if (!empty($errors)) {
163
+                    throw new \RuntimeException($this->l10n->t('Mail could not be sent. Check your mail server log'));
164
+                }
165
+                return new DataResponse();
166
+            } catch (\Exception $e) {
167
+                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);
168
+            }
169
+        }
170
+
171
+        return new DataResponse($this->l10n->t('You need to set your user email before being able to send test emails.'), Http::STATUS_BAD_REQUEST);
172
+    }
173 173
 
174 174
 }
Please login to merge, or discard this patch.
apps/sharebymail/lib/ShareByMailProvider.php 1 patch
Indentation   +838 added lines, -838 removed lines patch added patch discarded remove patch
@@ -51,856 +51,856 @@
 block discarded – undo
51 51
  */
52 52
 class ShareByMailProvider implements IShareProvider {
53 53
 
54
-	/** @var  IDBConnection */
55
-	private $dbConnection;
56
-
57
-	/** @var ILogger */
58
-	private $logger;
59
-
60
-	/** @var ISecureRandom */
61
-	private $secureRandom;
62
-
63
-	/** @var IUserManager */
64
-	private $userManager;
65
-
66
-	/** @var IRootFolder */
67
-	private $rootFolder;
68
-
69
-	/** @var IL10N */
70
-	private $l;
71
-
72
-	/** @var IMailer */
73
-	private $mailer;
74
-
75
-	/** @var IURLGenerator */
76
-	private $urlGenerator;
77
-
78
-	/** @var IManager  */
79
-	private $activityManager;
80
-
81
-	/** @var SettingsManager */
82
-	private $settingsManager;
83
-
84
-	/** @var Defaults */
85
-	private $defaults;
86
-
87
-	/**
88
-	 * Return the identifier of this provider.
89
-	 *
90
-	 * @return string Containing only [a-zA-Z0-9]
91
-	 */
92
-	public function identifier() {
93
-		return 'ocMailShare';
94
-	}
95
-
96
-	/**
97
-	 * DefaultShareProvider constructor.
98
-	 *
99
-	 * @param IDBConnection $connection
100
-	 * @param ISecureRandom $secureRandom
101
-	 * @param IUserManager $userManager
102
-	 * @param IRootFolder $rootFolder
103
-	 * @param IL10N $l
104
-	 * @param ILogger $logger
105
-	 * @param IMailer $mailer
106
-	 * @param IURLGenerator $urlGenerator
107
-	 * @param IManager $activityManager
108
-	 * @param SettingsManager $settingsManager
109
-	 * @param Defaults $defaults
110
-	 */
111
-	public function __construct(
112
-		IDBConnection $connection,
113
-		ISecureRandom $secureRandom,
114
-		IUserManager $userManager,
115
-		IRootFolder $rootFolder,
116
-		IL10N $l,
117
-		ILogger $logger,
118
-		IMailer $mailer,
119
-		IURLGenerator $urlGenerator,
120
-		IManager $activityManager,
121
-		SettingsManager $settingsManager,
122
-		Defaults $defaults
123
-	) {
124
-		$this->dbConnection = $connection;
125
-		$this->secureRandom = $secureRandom;
126
-		$this->userManager = $userManager;
127
-		$this->rootFolder = $rootFolder;
128
-		$this->l = $l;
129
-		$this->logger = $logger;
130
-		$this->mailer = $mailer;
131
-		$this->urlGenerator = $urlGenerator;
132
-		$this->activityManager = $activityManager;
133
-		$this->settingsManager = $settingsManager;
134
-		$this->defaults = $defaults;
135
-	}
136
-
137
-	/**
138
-	 * Share a path
139
-	 *
140
-	 * @param IShare $share
141
-	 * @return IShare The share object
142
-	 * @throws ShareNotFound
143
-	 * @throws \Exception
144
-	 */
145
-	public function create(IShare $share) {
146
-
147
-		$shareWith = $share->getSharedWith();
148
-		/*
54
+    /** @var  IDBConnection */
55
+    private $dbConnection;
56
+
57
+    /** @var ILogger */
58
+    private $logger;
59
+
60
+    /** @var ISecureRandom */
61
+    private $secureRandom;
62
+
63
+    /** @var IUserManager */
64
+    private $userManager;
65
+
66
+    /** @var IRootFolder */
67
+    private $rootFolder;
68
+
69
+    /** @var IL10N */
70
+    private $l;
71
+
72
+    /** @var IMailer */
73
+    private $mailer;
74
+
75
+    /** @var IURLGenerator */
76
+    private $urlGenerator;
77
+
78
+    /** @var IManager  */
79
+    private $activityManager;
80
+
81
+    /** @var SettingsManager */
82
+    private $settingsManager;
83
+
84
+    /** @var Defaults */
85
+    private $defaults;
86
+
87
+    /**
88
+     * Return the identifier of this provider.
89
+     *
90
+     * @return string Containing only [a-zA-Z0-9]
91
+     */
92
+    public function identifier() {
93
+        return 'ocMailShare';
94
+    }
95
+
96
+    /**
97
+     * DefaultShareProvider constructor.
98
+     *
99
+     * @param IDBConnection $connection
100
+     * @param ISecureRandom $secureRandom
101
+     * @param IUserManager $userManager
102
+     * @param IRootFolder $rootFolder
103
+     * @param IL10N $l
104
+     * @param ILogger $logger
105
+     * @param IMailer $mailer
106
+     * @param IURLGenerator $urlGenerator
107
+     * @param IManager $activityManager
108
+     * @param SettingsManager $settingsManager
109
+     * @param Defaults $defaults
110
+     */
111
+    public function __construct(
112
+        IDBConnection $connection,
113
+        ISecureRandom $secureRandom,
114
+        IUserManager $userManager,
115
+        IRootFolder $rootFolder,
116
+        IL10N $l,
117
+        ILogger $logger,
118
+        IMailer $mailer,
119
+        IURLGenerator $urlGenerator,
120
+        IManager $activityManager,
121
+        SettingsManager $settingsManager,
122
+        Defaults $defaults
123
+    ) {
124
+        $this->dbConnection = $connection;
125
+        $this->secureRandom = $secureRandom;
126
+        $this->userManager = $userManager;
127
+        $this->rootFolder = $rootFolder;
128
+        $this->l = $l;
129
+        $this->logger = $logger;
130
+        $this->mailer = $mailer;
131
+        $this->urlGenerator = $urlGenerator;
132
+        $this->activityManager = $activityManager;
133
+        $this->settingsManager = $settingsManager;
134
+        $this->defaults = $defaults;
135
+    }
136
+
137
+    /**
138
+     * Share a path
139
+     *
140
+     * @param IShare $share
141
+     * @return IShare The share object
142
+     * @throws ShareNotFound
143
+     * @throws \Exception
144
+     */
145
+    public function create(IShare $share) {
146
+
147
+        $shareWith = $share->getSharedWith();
148
+        /*
149 149
 		 * Check if file is not already shared with the remote user
150 150
 		 */
151
-		$alreadyShared = $this->getSharedWith($shareWith, \OCP\Share::SHARE_TYPE_EMAIL, $share->getNode(), 1, 0);
152
-		if (!empty($alreadyShared)) {
153
-			$message = 'Sharing %s failed, this item is already shared with %s';
154
-			$message_t = $this->l->t('Sharing %s failed, this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
155
-			$this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
156
-			throw new \Exception($message_t);
157
-		}
158
-
159
-		$shareId = $this->createMailShare($share);
160
-		$this->createActivity($share);
161
-		$data = $this->getRawShare($shareId);
162
-		return $this->createShareObject($data);
163
-
164
-	}
165
-
166
-	/**
167
-	 * create activity if a file/folder was shared by mail
168
-	 *
169
-	 * @param IShare $share
170
-	 */
171
-	protected function createActivity(IShare $share) {
172
-
173
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
174
-
175
-		$this->publishActivity(
176
-			Activity::SUBJECT_SHARED_EMAIL_SELF,
177
-			[$userFolder->getRelativePath($share->getNode()->getPath()), $share->getSharedWith()],
178
-			$share->getSharedBy(),
179
-			$share->getNode()->getId(),
180
-			$userFolder->getRelativePath($share->getNode()->getPath())
181
-		);
182
-
183
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
184
-			$ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
185
-			$fileId = $share->getNode()->getId();
186
-			$nodes = $ownerFolder->getById($fileId);
187
-			$ownerPath = $nodes[0]->getPath();
188
-			$this->publishActivity(
189
-				Activity::SUBJECT_SHARED_EMAIL_BY,
190
-				[$ownerFolder->getRelativePath($ownerPath), $share->getSharedWith(), $share->getSharedBy()],
191
-				$share->getShareOwner(),
192
-				$fileId,
193
-				$ownerFolder->getRelativePath($ownerPath)
194
-			);
195
-		}
196
-
197
-	}
198
-
199
-	/**
200
-	 * publish activity if a file/folder was shared by mail
201
-	 *
202
-	 * @param $subject
203
-	 * @param $parameters
204
-	 * @param $affectedUser
205
-	 * @param $fileId
206
-	 * @param $filePath
207
-	 */
208
-	protected function publishActivity($subject, $parameters, $affectedUser, $fileId, $filePath) {
209
-		$event = $this->activityManager->generateEvent();
210
-		$event->setApp('sharebymail')
211
-			->setType('shared')
212
-			->setSubject($subject, $parameters)
213
-			->setAffectedUser($affectedUser)
214
-			->setObject('files', $fileId, $filePath);
215
-		$this->activityManager->publish($event);
216
-
217
-	}
218
-
219
-	/**
220
-	 * @param IShare $share
221
-	 * @return int
222
-	 * @throws \Exception
223
-	 */
224
-	protected function createMailShare(IShare $share) {
225
-		$share->setToken($this->generateToken());
226
-		$shareId = $this->addShareToDB(
227
-			$share->getNodeId(),
228
-			$share->getNodeType(),
229
-			$share->getSharedWith(),
230
-			$share->getSharedBy(),
231
-			$share->getShareOwner(),
232
-			$share->getPermissions(),
233
-			$share->getToken()
234
-		);
235
-
236
-		try {
237
-			$link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
238
-				['token' => $share->getToken()]);
239
-			$this->sendMailNotification(
240
-				$share->getNode()->getName(),
241
-				$link,
242
-				$share->getShareOwner(),
243
-				$share->getSharedBy(),
244
-				$share->getSharedWith()
245
-			);
246
-		} catch (HintException $hintException) {
247
-			$this->logger->error('Failed to send share by mail: ' . $hintException->getMessage());
248
-			$this->removeShareFromTable($shareId);
249
-			throw $hintException;
250
-		} catch (\Exception $e) {
251
-			$this->logger->error('Failed to send share by mail: ' . $e->getMessage());
252
-			$this->removeShareFromTable($shareId);
253
-			throw new HintException('Failed to send share by mail',
254
-				$this->l->t('Failed to send share by E-mail'));
255
-		}
256
-
257
-		return $shareId;
258
-
259
-	}
260
-
261
-	/**
262
-	 * @param string $filename
263
-	 * @param string $link
264
-	 * @param string $owner
265
-	 * @param string $initiator
266
-	 * @param string $shareWith
267
-	 * @throws \Exception If mail couldn't be sent
268
-	 */
269
-	protected function sendMailNotification($filename,
270
-											$link,
271
-											$owner,
272
-											$initiator,
273
-											$shareWith) {
274
-		$ownerUser = $this->userManager->get($owner);
275
-		$initiatorUser = $this->userManager->get($initiator);
276
-		$ownerDisplayName = ($ownerUser instanceof IUser) ? $ownerUser->getDisplayName() : $owner;
277
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
278
-		if ($owner === $initiator) {
279
-			$subject = (string)$this->l->t('%s shared »%s« with you', array($ownerDisplayName, $filename));
280
-		} else {
281
-			$subject = (string)$this->l->t('%s shared »%s« with you on behalf of %s', array($ownerDisplayName, $filename, $initiatorDisplayName));
282
-		}
283
-
284
-		$message = $this->mailer->createMessage();
285
-
286
-		$emailTemplate = $this->mailer->createEMailTemplate();
287
-
288
-		$emailTemplate->addHeader();
289
-		$emailTemplate->addHeading($this->l->t('%s shared »%s« with you', [$ownerDisplayName, $filename]), false);
290
-
291
-		if ($owner === $initiator) {
292
-			$text = $this->l->t('%s shared »%s« with you.', [$ownerDisplayName, $filename]);
293
-		} else {
294
-			$text= $this->l->t('%s shared »%s« with you on behalf of %s.', [$ownerDisplayName, $filename, $initiator]);
295
-		}
296
-
297
-		$emailTemplate->addBodyText(
298
-			$text . ' ' . $this->l->t('Click the button below to open it.'),
299
-			$text
300
-		);
301
-
302
-		$emailTemplate->addBodyButton(
303
-			$this->l->t('Open »%s«', [$filename]),
304
-			$link
305
-		);
306
-
307
-		$message->setTo([$shareWith]);
308
-
309
-		// The "From" contains the sharers name
310
-		$instanceName = $this->defaults->getName();
311
-		$senderName = $this->l->t(
312
-			'%s via %s',
313
-			[
314
-				$ownerDisplayName,
315
-				$instanceName
316
-			]
317
-		);
318
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
319
-
320
-		// The "Reply-To" is set to the sharer if an mail address is configured
321
-		// also the default footer contains a "Do not reply" which needs to be adjusted.
322
-		$ownerEmail = $ownerUser->getEMailAddress();
323
-		if($ownerEmail !== null) {
324
-			$message->setReplyTo([$ownerEmail => $ownerDisplayName]);
325
-			$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
326
-		} else {
327
-			$emailTemplate->addFooter();
328
-		}
329
-
330
-		$message->setSubject($subject);
331
-		$message->setPlainBody($emailTemplate->renderText());
332
-		$message->setHtmlBody($emailTemplate->renderHtml());
333
-		$this->mailer->send($message);
334
-	}
335
-
336
-	/**
337
-	 * send password to recipient of a mail share
338
-	 *
339
-	 * @param string $filename
340
-	 * @param string $initiator
341
-	 * @param string $shareWith
342
-	 */
343
-	protected function sendPassword($filename, $initiator, $shareWith, $password) {
344
-
345
-		if ($this->settingsManager->sendPasswordByMail() === false) {
346
-			return;
347
-		}
348
-
349
-		$initiatorUser = $this->userManager->get($initiator);
350
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
351
-		$subject = (string)$this->l->t('Password to access »%s« shared to you by %s', [$filename, $initiatorDisplayName]);
352
-
353
-		$message = $this->mailer->createMessage();
354
-
355
-		$emailTemplate = $this->mailer->createEMailTemplate();
356
-
357
-		$emailTemplate->addHeader();
358
-		$emailTemplate->addHeading($this->l->t('Password to access »%s«', [$filename]));
359
-
360
-		$emailTemplate->addBodyText($this->l->t(
361
-			'%s shared »%s« with you. You should have already received a separate mail with a link to access it.',
362
-				[$initiatorDisplayName, $filename]
363
-		));
364
-		$emailTemplate->addBodyText($this->l->t('It is protected with the following password: %s', [$password]));
365
-
366
-		$emailTemplate->addFooter();
367
-
368
-		$message->setTo([$shareWith]);
369
-		$message->setSubject($subject);
370
-		$message->setBody($emailTemplate->renderText(), 'text/plain');
371
-		$message->setHtmlBody($emailTemplate->renderHtml());
372
-		$this->mailer->send($message);
373
-
374
-	}
375
-
376
-
377
-	/**
378
-	 * generate share token
379
-	 *
380
-	 * @return string
381
-	 */
382
-	protected function generateToken() {
383
-		$token = $this->secureRandom->generate(
384
-			15, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);
385
-		return $token;
386
-	}
387
-
388
-	/**
389
-	 * Get all children of this share
390
-	 *
391
-	 * @param IShare $parent
392
-	 * @return IShare[]
393
-	 */
394
-	public function getChildren(IShare $parent) {
395
-		$children = [];
396
-
397
-		$qb = $this->dbConnection->getQueryBuilder();
398
-		$qb->select('*')
399
-			->from('share')
400
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
401
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
402
-			->orderBy('id');
403
-
404
-		$cursor = $qb->execute();
405
-		while($data = $cursor->fetch()) {
406
-			$children[] = $this->createShareObject($data);
407
-		}
408
-		$cursor->closeCursor();
409
-
410
-		return $children;
411
-	}
412
-
413
-	/**
414
-	 * add share to the database and return the ID
415
-	 *
416
-	 * @param int $itemSource
417
-	 * @param string $itemType
418
-	 * @param string $shareWith
419
-	 * @param string $sharedBy
420
-	 * @param string $uidOwner
421
-	 * @param int $permissions
422
-	 * @param string $token
423
-	 * @return int
424
-	 */
425
-	protected function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
426
-		$qb = $this->dbConnection->getQueryBuilder();
427
-		$qb->insert('share')
428
-			->setValue('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
429
-			->setValue('item_type', $qb->createNamedParameter($itemType))
430
-			->setValue('item_source', $qb->createNamedParameter($itemSource))
431
-			->setValue('file_source', $qb->createNamedParameter($itemSource))
432
-			->setValue('share_with', $qb->createNamedParameter($shareWith))
433
-			->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
434
-			->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
435
-			->setValue('permissions', $qb->createNamedParameter($permissions))
436
-			->setValue('token', $qb->createNamedParameter($token))
437
-			->setValue('stime', $qb->createNamedParameter(time()));
438
-
439
-		/*
151
+        $alreadyShared = $this->getSharedWith($shareWith, \OCP\Share::SHARE_TYPE_EMAIL, $share->getNode(), 1, 0);
152
+        if (!empty($alreadyShared)) {
153
+            $message = 'Sharing %s failed, this item is already shared with %s';
154
+            $message_t = $this->l->t('Sharing %s failed, this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
155
+            $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
156
+            throw new \Exception($message_t);
157
+        }
158
+
159
+        $shareId = $this->createMailShare($share);
160
+        $this->createActivity($share);
161
+        $data = $this->getRawShare($shareId);
162
+        return $this->createShareObject($data);
163
+
164
+    }
165
+
166
+    /**
167
+     * create activity if a file/folder was shared by mail
168
+     *
169
+     * @param IShare $share
170
+     */
171
+    protected function createActivity(IShare $share) {
172
+
173
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
174
+
175
+        $this->publishActivity(
176
+            Activity::SUBJECT_SHARED_EMAIL_SELF,
177
+            [$userFolder->getRelativePath($share->getNode()->getPath()), $share->getSharedWith()],
178
+            $share->getSharedBy(),
179
+            $share->getNode()->getId(),
180
+            $userFolder->getRelativePath($share->getNode()->getPath())
181
+        );
182
+
183
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
184
+            $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
185
+            $fileId = $share->getNode()->getId();
186
+            $nodes = $ownerFolder->getById($fileId);
187
+            $ownerPath = $nodes[0]->getPath();
188
+            $this->publishActivity(
189
+                Activity::SUBJECT_SHARED_EMAIL_BY,
190
+                [$ownerFolder->getRelativePath($ownerPath), $share->getSharedWith(), $share->getSharedBy()],
191
+                $share->getShareOwner(),
192
+                $fileId,
193
+                $ownerFolder->getRelativePath($ownerPath)
194
+            );
195
+        }
196
+
197
+    }
198
+
199
+    /**
200
+     * publish activity if a file/folder was shared by mail
201
+     *
202
+     * @param $subject
203
+     * @param $parameters
204
+     * @param $affectedUser
205
+     * @param $fileId
206
+     * @param $filePath
207
+     */
208
+    protected function publishActivity($subject, $parameters, $affectedUser, $fileId, $filePath) {
209
+        $event = $this->activityManager->generateEvent();
210
+        $event->setApp('sharebymail')
211
+            ->setType('shared')
212
+            ->setSubject($subject, $parameters)
213
+            ->setAffectedUser($affectedUser)
214
+            ->setObject('files', $fileId, $filePath);
215
+        $this->activityManager->publish($event);
216
+
217
+    }
218
+
219
+    /**
220
+     * @param IShare $share
221
+     * @return int
222
+     * @throws \Exception
223
+     */
224
+    protected function createMailShare(IShare $share) {
225
+        $share->setToken($this->generateToken());
226
+        $shareId = $this->addShareToDB(
227
+            $share->getNodeId(),
228
+            $share->getNodeType(),
229
+            $share->getSharedWith(),
230
+            $share->getSharedBy(),
231
+            $share->getShareOwner(),
232
+            $share->getPermissions(),
233
+            $share->getToken()
234
+        );
235
+
236
+        try {
237
+            $link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
238
+                ['token' => $share->getToken()]);
239
+            $this->sendMailNotification(
240
+                $share->getNode()->getName(),
241
+                $link,
242
+                $share->getShareOwner(),
243
+                $share->getSharedBy(),
244
+                $share->getSharedWith()
245
+            );
246
+        } catch (HintException $hintException) {
247
+            $this->logger->error('Failed to send share by mail: ' . $hintException->getMessage());
248
+            $this->removeShareFromTable($shareId);
249
+            throw $hintException;
250
+        } catch (\Exception $e) {
251
+            $this->logger->error('Failed to send share by mail: ' . $e->getMessage());
252
+            $this->removeShareFromTable($shareId);
253
+            throw new HintException('Failed to send share by mail',
254
+                $this->l->t('Failed to send share by E-mail'));
255
+        }
256
+
257
+        return $shareId;
258
+
259
+    }
260
+
261
+    /**
262
+     * @param string $filename
263
+     * @param string $link
264
+     * @param string $owner
265
+     * @param string $initiator
266
+     * @param string $shareWith
267
+     * @throws \Exception If mail couldn't be sent
268
+     */
269
+    protected function sendMailNotification($filename,
270
+                                            $link,
271
+                                            $owner,
272
+                                            $initiator,
273
+                                            $shareWith) {
274
+        $ownerUser = $this->userManager->get($owner);
275
+        $initiatorUser = $this->userManager->get($initiator);
276
+        $ownerDisplayName = ($ownerUser instanceof IUser) ? $ownerUser->getDisplayName() : $owner;
277
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
278
+        if ($owner === $initiator) {
279
+            $subject = (string)$this->l->t('%s shared »%s« with you', array($ownerDisplayName, $filename));
280
+        } else {
281
+            $subject = (string)$this->l->t('%s shared »%s« with you on behalf of %s', array($ownerDisplayName, $filename, $initiatorDisplayName));
282
+        }
283
+
284
+        $message = $this->mailer->createMessage();
285
+
286
+        $emailTemplate = $this->mailer->createEMailTemplate();
287
+
288
+        $emailTemplate->addHeader();
289
+        $emailTemplate->addHeading($this->l->t('%s shared »%s« with you', [$ownerDisplayName, $filename]), false);
290
+
291
+        if ($owner === $initiator) {
292
+            $text = $this->l->t('%s shared »%s« with you.', [$ownerDisplayName, $filename]);
293
+        } else {
294
+            $text= $this->l->t('%s shared »%s« with you on behalf of %s.', [$ownerDisplayName, $filename, $initiator]);
295
+        }
296
+
297
+        $emailTemplate->addBodyText(
298
+            $text . ' ' . $this->l->t('Click the button below to open it.'),
299
+            $text
300
+        );
301
+
302
+        $emailTemplate->addBodyButton(
303
+            $this->l->t('Open »%s«', [$filename]),
304
+            $link
305
+        );
306
+
307
+        $message->setTo([$shareWith]);
308
+
309
+        // The "From" contains the sharers name
310
+        $instanceName = $this->defaults->getName();
311
+        $senderName = $this->l->t(
312
+            '%s via %s',
313
+            [
314
+                $ownerDisplayName,
315
+                $instanceName
316
+            ]
317
+        );
318
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
319
+
320
+        // The "Reply-To" is set to the sharer if an mail address is configured
321
+        // also the default footer contains a "Do not reply" which needs to be adjusted.
322
+        $ownerEmail = $ownerUser->getEMailAddress();
323
+        if($ownerEmail !== null) {
324
+            $message->setReplyTo([$ownerEmail => $ownerDisplayName]);
325
+            $emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
326
+        } else {
327
+            $emailTemplate->addFooter();
328
+        }
329
+
330
+        $message->setSubject($subject);
331
+        $message->setPlainBody($emailTemplate->renderText());
332
+        $message->setHtmlBody($emailTemplate->renderHtml());
333
+        $this->mailer->send($message);
334
+    }
335
+
336
+    /**
337
+     * send password to recipient of a mail share
338
+     *
339
+     * @param string $filename
340
+     * @param string $initiator
341
+     * @param string $shareWith
342
+     */
343
+    protected function sendPassword($filename, $initiator, $shareWith, $password) {
344
+
345
+        if ($this->settingsManager->sendPasswordByMail() === false) {
346
+            return;
347
+        }
348
+
349
+        $initiatorUser = $this->userManager->get($initiator);
350
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
351
+        $subject = (string)$this->l->t('Password to access »%s« shared to you by %s', [$filename, $initiatorDisplayName]);
352
+
353
+        $message = $this->mailer->createMessage();
354
+
355
+        $emailTemplate = $this->mailer->createEMailTemplate();
356
+
357
+        $emailTemplate->addHeader();
358
+        $emailTemplate->addHeading($this->l->t('Password to access »%s«', [$filename]));
359
+
360
+        $emailTemplate->addBodyText($this->l->t(
361
+            '%s shared »%s« with you. You should have already received a separate mail with a link to access it.',
362
+                [$initiatorDisplayName, $filename]
363
+        ));
364
+        $emailTemplate->addBodyText($this->l->t('It is protected with the following password: %s', [$password]));
365
+
366
+        $emailTemplate->addFooter();
367
+
368
+        $message->setTo([$shareWith]);
369
+        $message->setSubject($subject);
370
+        $message->setBody($emailTemplate->renderText(), 'text/plain');
371
+        $message->setHtmlBody($emailTemplate->renderHtml());
372
+        $this->mailer->send($message);
373
+
374
+    }
375
+
376
+
377
+    /**
378
+     * generate share token
379
+     *
380
+     * @return string
381
+     */
382
+    protected function generateToken() {
383
+        $token = $this->secureRandom->generate(
384
+            15, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);
385
+        return $token;
386
+    }
387
+
388
+    /**
389
+     * Get all children of this share
390
+     *
391
+     * @param IShare $parent
392
+     * @return IShare[]
393
+     */
394
+    public function getChildren(IShare $parent) {
395
+        $children = [];
396
+
397
+        $qb = $this->dbConnection->getQueryBuilder();
398
+        $qb->select('*')
399
+            ->from('share')
400
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
401
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
402
+            ->orderBy('id');
403
+
404
+        $cursor = $qb->execute();
405
+        while($data = $cursor->fetch()) {
406
+            $children[] = $this->createShareObject($data);
407
+        }
408
+        $cursor->closeCursor();
409
+
410
+        return $children;
411
+    }
412
+
413
+    /**
414
+     * add share to the database and return the ID
415
+     *
416
+     * @param int $itemSource
417
+     * @param string $itemType
418
+     * @param string $shareWith
419
+     * @param string $sharedBy
420
+     * @param string $uidOwner
421
+     * @param int $permissions
422
+     * @param string $token
423
+     * @return int
424
+     */
425
+    protected function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
426
+        $qb = $this->dbConnection->getQueryBuilder();
427
+        $qb->insert('share')
428
+            ->setValue('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
429
+            ->setValue('item_type', $qb->createNamedParameter($itemType))
430
+            ->setValue('item_source', $qb->createNamedParameter($itemSource))
431
+            ->setValue('file_source', $qb->createNamedParameter($itemSource))
432
+            ->setValue('share_with', $qb->createNamedParameter($shareWith))
433
+            ->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
434
+            ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
435
+            ->setValue('permissions', $qb->createNamedParameter($permissions))
436
+            ->setValue('token', $qb->createNamedParameter($token))
437
+            ->setValue('stime', $qb->createNamedParameter(time()));
438
+
439
+        /*
440 440
 		 * Added to fix https://github.com/owncloud/core/issues/22215
441 441
 		 * Can be removed once we get rid of ajax/share.php
442 442
 		 */
443
-		$qb->setValue('file_target', $qb->createNamedParameter(''));
443
+        $qb->setValue('file_target', $qb->createNamedParameter(''));
444 444
 
445
-		$qb->execute();
446
-		$id = $qb->getLastInsertId();
445
+        $qb->execute();
446
+        $id = $qb->getLastInsertId();
447 447
 
448
-		return (int)$id;
449
-	}
448
+        return (int)$id;
449
+    }
450 450
 
451
-	/**
452
-	 * Update a share
453
-	 *
454
-	 * @param IShare $share
455
-	 * @param string|null $plainTextPassword
456
-	 * @return IShare The share object
457
-	 */
458
-	public function update(IShare $share, $plainTextPassword = null) {
451
+    /**
452
+     * Update a share
453
+     *
454
+     * @param IShare $share
455
+     * @param string|null $plainTextPassword
456
+     * @return IShare The share object
457
+     */
458
+    public function update(IShare $share, $plainTextPassword = null) {
459 459
 
460
-		$originalShare = $this->getShareById($share->getId());
460
+        $originalShare = $this->getShareById($share->getId());
461 461
 
462
-		// a real password was given
463
-		$validPassword = $plainTextPassword !== null && $plainTextPassword !== '';
462
+        // a real password was given
463
+        $validPassword = $plainTextPassword !== null && $plainTextPassword !== '';
464 464
 
465
-		if($validPassword && $originalShare->getPassword() !== $share->getPassword()) {
466
-			$this->sendPassword($share->getNode()->getName(), $share->getSharedBy(), $share->getSharedWith(), $plainTextPassword);
467
-		}
468
-		/*
465
+        if($validPassword && $originalShare->getPassword() !== $share->getPassword()) {
466
+            $this->sendPassword($share->getNode()->getName(), $share->getSharedBy(), $share->getSharedWith(), $plainTextPassword);
467
+        }
468
+        /*
469 469
 		 * We allow updating the permissions and password of mail shares
470 470
 		 */
471
-		$qb = $this->dbConnection->getQueryBuilder();
472
-		$qb->update('share')
473
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
474
-			->set('permissions', $qb->createNamedParameter($share->getPermissions()))
475
-			->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
476
-			->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
477
-			->set('password', $qb->createNamedParameter($share->getPassword()))
478
-			->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
479
-			->execute();
480
-
481
-		return $share;
482
-	}
483
-
484
-	/**
485
-	 * @inheritdoc
486
-	 */
487
-	public function move(IShare $share, $recipient) {
488
-		/**
489
-		 * nothing to do here, mail shares are only outgoing shares
490
-		 */
491
-		return $share;
492
-	}
493
-
494
-	/**
495
-	 * Delete a share (owner unShares the file)
496
-	 *
497
-	 * @param IShare $share
498
-	 */
499
-	public function delete(IShare $share) {
500
-		$this->removeShareFromTable($share->getId());
501
-	}
502
-
503
-	/**
504
-	 * @inheritdoc
505
-	 */
506
-	public function deleteFromSelf(IShare $share, $recipient) {
507
-		// nothing to do here, mail shares are only outgoing shares
508
-		return;
509
-	}
510
-
511
-	/**
512
-	 * @inheritdoc
513
-	 */
514
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
515
-		$qb = $this->dbConnection->getQueryBuilder();
516
-		$qb->select('*')
517
-			->from('share');
518
-
519
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
520
-
521
-		/**
522
-		 * Reshares for this user are shares where they are the owner.
523
-		 */
524
-		if ($reshares === false) {
525
-			//Special case for old shares created via the web UI
526
-			$or1 = $qb->expr()->andX(
527
-				$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
528
-				$qb->expr()->isNull('uid_initiator')
529
-			);
530
-
531
-			$qb->andWhere(
532
-				$qb->expr()->orX(
533
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
534
-					$or1
535
-				)
536
-			);
537
-		} else {
538
-			$qb->andWhere(
539
-				$qb->expr()->orX(
540
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
541
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
542
-				)
543
-			);
544
-		}
545
-
546
-		if ($node !== null) {
547
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
548
-		}
549
-
550
-		if ($limit !== -1) {
551
-			$qb->setMaxResults($limit);
552
-		}
553
-
554
-		$qb->setFirstResult($offset);
555
-		$qb->orderBy('id');
556
-
557
-		$cursor = $qb->execute();
558
-		$shares = [];
559
-		while($data = $cursor->fetch()) {
560
-			$shares[] = $this->createShareObject($data);
561
-		}
562
-		$cursor->closeCursor();
563
-
564
-		return $shares;
565
-	}
566
-
567
-	/**
568
-	 * @inheritdoc
569
-	 */
570
-	public function getShareById($id, $recipientId = null) {
571
-		$qb = $this->dbConnection->getQueryBuilder();
572
-
573
-		$qb->select('*')
574
-			->from('share')
575
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
576
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
577
-
578
-		$cursor = $qb->execute();
579
-		$data = $cursor->fetch();
580
-		$cursor->closeCursor();
581
-
582
-		if ($data === false) {
583
-			throw new ShareNotFound();
584
-		}
585
-
586
-		try {
587
-			$share = $this->createShareObject($data);
588
-		} catch (InvalidShare $e) {
589
-			throw new ShareNotFound();
590
-		}
591
-
592
-		return $share;
593
-	}
594
-
595
-	/**
596
-	 * Get shares for a given path
597
-	 *
598
-	 * @param \OCP\Files\Node $path
599
-	 * @return IShare[]
600
-	 */
601
-	public function getSharesByPath(Node $path) {
602
-		$qb = $this->dbConnection->getQueryBuilder();
603
-
604
-		$cursor = $qb->select('*')
605
-			->from('share')
606
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
607
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
608
-			->execute();
609
-
610
-		$shares = [];
611
-		while($data = $cursor->fetch()) {
612
-			$shares[] = $this->createShareObject($data);
613
-		}
614
-		$cursor->closeCursor();
615
-
616
-		return $shares;
617
-	}
618
-
619
-	/**
620
-	 * @inheritdoc
621
-	 */
622
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
623
-		/** @var IShare[] $shares */
624
-		$shares = [];
625
-
626
-		//Get shares directly with this user
627
-		$qb = $this->dbConnection->getQueryBuilder();
628
-		$qb->select('*')
629
-			->from('share');
630
-
631
-		// Order by id
632
-		$qb->orderBy('id');
633
-
634
-		// Set limit and offset
635
-		if ($limit !== -1) {
636
-			$qb->setMaxResults($limit);
637
-		}
638
-		$qb->setFirstResult($offset);
639
-
640
-		$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
641
-		$qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
642
-
643
-		// Filter by node if provided
644
-		if ($node !== null) {
645
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
646
-		}
647
-
648
-		$cursor = $qb->execute();
649
-
650
-		while($data = $cursor->fetch()) {
651
-			$shares[] = $this->createShareObject($data);
652
-		}
653
-		$cursor->closeCursor();
654
-
655
-
656
-		return $shares;
657
-	}
658
-
659
-	/**
660
-	 * Get a share by token
661
-	 *
662
-	 * @param string $token
663
-	 * @return IShare
664
-	 * @throws ShareNotFound
665
-	 */
666
-	public function getShareByToken($token) {
667
-		$qb = $this->dbConnection->getQueryBuilder();
668
-
669
-		$cursor = $qb->select('*')
670
-			->from('share')
671
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
672
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
673
-			->execute();
674
-
675
-		$data = $cursor->fetch();
676
-
677
-		if ($data === false) {
678
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
679
-		}
680
-
681
-		try {
682
-			$share = $this->createShareObject($data);
683
-		} catch (InvalidShare $e) {
684
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
685
-		}
686
-
687
-		return $share;
688
-	}
689
-
690
-	/**
691
-	 * remove share from table
692
-	 *
693
-	 * @param string $shareId
694
-	 */
695
-	protected function removeShareFromTable($shareId) {
696
-		$qb = $this->dbConnection->getQueryBuilder();
697
-		$qb->delete('share')
698
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
699
-		$qb->execute();
700
-	}
701
-
702
-	/**
703
-	 * Create a share object from an database row
704
-	 *
705
-	 * @param array $data
706
-	 * @return IShare
707
-	 * @throws InvalidShare
708
-	 * @throws ShareNotFound
709
-	 */
710
-	protected function createShareObject($data) {
711
-
712
-		$share = new Share($this->rootFolder, $this->userManager);
713
-		$share->setId((int)$data['id'])
714
-			->setShareType((int)$data['share_type'])
715
-			->setPermissions((int)$data['permissions'])
716
-			->setTarget($data['file_target'])
717
-			->setMailSend((bool)$data['mail_send'])
718
-			->setToken($data['token']);
719
-
720
-		$shareTime = new \DateTime();
721
-		$shareTime->setTimestamp((int)$data['stime']);
722
-		$share->setShareTime($shareTime);
723
-		$share->setSharedWith($data['share_with']);
724
-		$share->setPassword($data['password']);
725
-
726
-		if ($data['uid_initiator'] !== null) {
727
-			$share->setShareOwner($data['uid_owner']);
728
-			$share->setSharedBy($data['uid_initiator']);
729
-		} else {
730
-			//OLD SHARE
731
-			$share->setSharedBy($data['uid_owner']);
732
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
733
-
734
-			$owner = $path->getOwner();
735
-			$share->setShareOwner($owner->getUID());
736
-		}
737
-
738
-		if ($data['expiration'] !== null) {
739
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
740
-			if ($expiration !== false) {
741
-				$share->setExpirationDate($expiration);
742
-			}
743
-		}
744
-
745
-		$share->setNodeId((int)$data['file_source']);
746
-		$share->setNodeType($data['item_type']);
747
-
748
-		$share->setProviderId($this->identifier());
749
-
750
-		return $share;
751
-	}
752
-
753
-	/**
754
-	 * Get the node with file $id for $user
755
-	 *
756
-	 * @param string $userId
757
-	 * @param int $id
758
-	 * @return \OCP\Files\File|\OCP\Files\Folder
759
-	 * @throws InvalidShare
760
-	 */
761
-	private function getNode($userId, $id) {
762
-		try {
763
-			$userFolder = $this->rootFolder->getUserFolder($userId);
764
-		} catch (NotFoundException $e) {
765
-			throw new InvalidShare();
766
-		}
767
-
768
-		$nodes = $userFolder->getById($id);
769
-
770
-		if (empty($nodes)) {
771
-			throw new InvalidShare();
772
-		}
773
-
774
-		return $nodes[0];
775
-	}
776
-
777
-	/**
778
-	 * A user is deleted from the system
779
-	 * So clean up the relevant shares.
780
-	 *
781
-	 * @param string $uid
782
-	 * @param int $shareType
783
-	 */
784
-	public function userDeleted($uid, $shareType) {
785
-		$qb = $this->dbConnection->getQueryBuilder();
786
-
787
-		$qb->delete('share')
788
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
789
-			->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
790
-			->execute();
791
-	}
792
-
793
-	/**
794
-	 * This provider does not support group shares
795
-	 *
796
-	 * @param string $gid
797
-	 */
798
-	public function groupDeleted($gid) {
799
-		return;
800
-	}
801
-
802
-	/**
803
-	 * This provider does not support group shares
804
-	 *
805
-	 * @param string $uid
806
-	 * @param string $gid
807
-	 */
808
-	public function userDeletedFromGroup($uid, $gid) {
809
-		return;
810
-	}
811
-
812
-	/**
813
-	 * get database row of a give share
814
-	 *
815
-	 * @param $id
816
-	 * @return array
817
-	 * @throws ShareNotFound
818
-	 */
819
-	protected function getRawShare($id) {
820
-
821
-		// Now fetch the inserted share and create a complete share object
822
-		$qb = $this->dbConnection->getQueryBuilder();
823
-		$qb->select('*')
824
-			->from('share')
825
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
826
-
827
-		$cursor = $qb->execute();
828
-		$data = $cursor->fetch();
829
-		$cursor->closeCursor();
830
-
831
-		if ($data === false) {
832
-			throw new ShareNotFound;
833
-		}
834
-
835
-		return $data;
836
-	}
837
-
838
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
839
-		$qb = $this->dbConnection->getQueryBuilder();
840
-		$qb->select('*')
841
-			->from('share', 's')
842
-			->andWhere($qb->expr()->orX(
843
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
844
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
845
-			))
846
-			->andWhere(
847
-				$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
848
-			);
849
-
850
-		/**
851
-		 * Reshares for this user are shares where they are the owner.
852
-		 */
853
-		if ($reshares === false) {
854
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
855
-		} else {
856
-			$qb->andWhere(
857
-				$qb->expr()->orX(
858
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
859
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
860
-				)
861
-			);
862
-		}
863
-
864
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
865
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
866
-
867
-		$qb->orderBy('id');
868
-
869
-		$cursor = $qb->execute();
870
-		$shares = [];
871
-		while ($data = $cursor->fetch()) {
872
-			$shares[$data['fileid']][] = $this->createShareObject($data);
873
-		}
874
-		$cursor->closeCursor();
875
-
876
-		return $shares;
877
-	}
878
-
879
-	/**
880
-	 * @inheritdoc
881
-	 */
882
-	public function getAccessList($nodes, $currentAccess) {
883
-		$ids = [];
884
-		foreach ($nodes as $node) {
885
-			$ids[] = $node->getId();
886
-		}
887
-
888
-		$qb = $this->dbConnection->getQueryBuilder();
889
-		$qb->select('share_with')
890
-			->from('share')
891
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
892
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
893
-			->andWhere($qb->expr()->orX(
894
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
895
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
896
-			))
897
-			->setMaxResults(1);
898
-		$cursor = $qb->execute();
899
-
900
-		$mail = $cursor->fetch() !== false;
901
-		$cursor->closeCursor();
902
-
903
-		return ['public' => $mail];
904
-	}
471
+        $qb = $this->dbConnection->getQueryBuilder();
472
+        $qb->update('share')
473
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
474
+            ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
475
+            ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
476
+            ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
477
+            ->set('password', $qb->createNamedParameter($share->getPassword()))
478
+            ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
479
+            ->execute();
480
+
481
+        return $share;
482
+    }
483
+
484
+    /**
485
+     * @inheritdoc
486
+     */
487
+    public function move(IShare $share, $recipient) {
488
+        /**
489
+         * nothing to do here, mail shares are only outgoing shares
490
+         */
491
+        return $share;
492
+    }
493
+
494
+    /**
495
+     * Delete a share (owner unShares the file)
496
+     *
497
+     * @param IShare $share
498
+     */
499
+    public function delete(IShare $share) {
500
+        $this->removeShareFromTable($share->getId());
501
+    }
502
+
503
+    /**
504
+     * @inheritdoc
505
+     */
506
+    public function deleteFromSelf(IShare $share, $recipient) {
507
+        // nothing to do here, mail shares are only outgoing shares
508
+        return;
509
+    }
510
+
511
+    /**
512
+     * @inheritdoc
513
+     */
514
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
515
+        $qb = $this->dbConnection->getQueryBuilder();
516
+        $qb->select('*')
517
+            ->from('share');
518
+
519
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
520
+
521
+        /**
522
+         * Reshares for this user are shares where they are the owner.
523
+         */
524
+        if ($reshares === false) {
525
+            //Special case for old shares created via the web UI
526
+            $or1 = $qb->expr()->andX(
527
+                $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
528
+                $qb->expr()->isNull('uid_initiator')
529
+            );
530
+
531
+            $qb->andWhere(
532
+                $qb->expr()->orX(
533
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
534
+                    $or1
535
+                )
536
+            );
537
+        } else {
538
+            $qb->andWhere(
539
+                $qb->expr()->orX(
540
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
541
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
542
+                )
543
+            );
544
+        }
545
+
546
+        if ($node !== null) {
547
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
548
+        }
549
+
550
+        if ($limit !== -1) {
551
+            $qb->setMaxResults($limit);
552
+        }
553
+
554
+        $qb->setFirstResult($offset);
555
+        $qb->orderBy('id');
556
+
557
+        $cursor = $qb->execute();
558
+        $shares = [];
559
+        while($data = $cursor->fetch()) {
560
+            $shares[] = $this->createShareObject($data);
561
+        }
562
+        $cursor->closeCursor();
563
+
564
+        return $shares;
565
+    }
566
+
567
+    /**
568
+     * @inheritdoc
569
+     */
570
+    public function getShareById($id, $recipientId = null) {
571
+        $qb = $this->dbConnection->getQueryBuilder();
572
+
573
+        $qb->select('*')
574
+            ->from('share')
575
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
576
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
577
+
578
+        $cursor = $qb->execute();
579
+        $data = $cursor->fetch();
580
+        $cursor->closeCursor();
581
+
582
+        if ($data === false) {
583
+            throw new ShareNotFound();
584
+        }
585
+
586
+        try {
587
+            $share = $this->createShareObject($data);
588
+        } catch (InvalidShare $e) {
589
+            throw new ShareNotFound();
590
+        }
591
+
592
+        return $share;
593
+    }
594
+
595
+    /**
596
+     * Get shares for a given path
597
+     *
598
+     * @param \OCP\Files\Node $path
599
+     * @return IShare[]
600
+     */
601
+    public function getSharesByPath(Node $path) {
602
+        $qb = $this->dbConnection->getQueryBuilder();
603
+
604
+        $cursor = $qb->select('*')
605
+            ->from('share')
606
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
607
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
608
+            ->execute();
609
+
610
+        $shares = [];
611
+        while($data = $cursor->fetch()) {
612
+            $shares[] = $this->createShareObject($data);
613
+        }
614
+        $cursor->closeCursor();
615
+
616
+        return $shares;
617
+    }
618
+
619
+    /**
620
+     * @inheritdoc
621
+     */
622
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
623
+        /** @var IShare[] $shares */
624
+        $shares = [];
625
+
626
+        //Get shares directly with this user
627
+        $qb = $this->dbConnection->getQueryBuilder();
628
+        $qb->select('*')
629
+            ->from('share');
630
+
631
+        // Order by id
632
+        $qb->orderBy('id');
633
+
634
+        // Set limit and offset
635
+        if ($limit !== -1) {
636
+            $qb->setMaxResults($limit);
637
+        }
638
+        $qb->setFirstResult($offset);
639
+
640
+        $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
641
+        $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
642
+
643
+        // Filter by node if provided
644
+        if ($node !== null) {
645
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
646
+        }
647
+
648
+        $cursor = $qb->execute();
649
+
650
+        while($data = $cursor->fetch()) {
651
+            $shares[] = $this->createShareObject($data);
652
+        }
653
+        $cursor->closeCursor();
654
+
655
+
656
+        return $shares;
657
+    }
658
+
659
+    /**
660
+     * Get a share by token
661
+     *
662
+     * @param string $token
663
+     * @return IShare
664
+     * @throws ShareNotFound
665
+     */
666
+    public function getShareByToken($token) {
667
+        $qb = $this->dbConnection->getQueryBuilder();
668
+
669
+        $cursor = $qb->select('*')
670
+            ->from('share')
671
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
672
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
673
+            ->execute();
674
+
675
+        $data = $cursor->fetch();
676
+
677
+        if ($data === false) {
678
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
679
+        }
680
+
681
+        try {
682
+            $share = $this->createShareObject($data);
683
+        } catch (InvalidShare $e) {
684
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
685
+        }
686
+
687
+        return $share;
688
+    }
689
+
690
+    /**
691
+     * remove share from table
692
+     *
693
+     * @param string $shareId
694
+     */
695
+    protected function removeShareFromTable($shareId) {
696
+        $qb = $this->dbConnection->getQueryBuilder();
697
+        $qb->delete('share')
698
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
699
+        $qb->execute();
700
+    }
701
+
702
+    /**
703
+     * Create a share object from an database row
704
+     *
705
+     * @param array $data
706
+     * @return IShare
707
+     * @throws InvalidShare
708
+     * @throws ShareNotFound
709
+     */
710
+    protected function createShareObject($data) {
711
+
712
+        $share = new Share($this->rootFolder, $this->userManager);
713
+        $share->setId((int)$data['id'])
714
+            ->setShareType((int)$data['share_type'])
715
+            ->setPermissions((int)$data['permissions'])
716
+            ->setTarget($data['file_target'])
717
+            ->setMailSend((bool)$data['mail_send'])
718
+            ->setToken($data['token']);
719
+
720
+        $shareTime = new \DateTime();
721
+        $shareTime->setTimestamp((int)$data['stime']);
722
+        $share->setShareTime($shareTime);
723
+        $share->setSharedWith($data['share_with']);
724
+        $share->setPassword($data['password']);
725
+
726
+        if ($data['uid_initiator'] !== null) {
727
+            $share->setShareOwner($data['uid_owner']);
728
+            $share->setSharedBy($data['uid_initiator']);
729
+        } else {
730
+            //OLD SHARE
731
+            $share->setSharedBy($data['uid_owner']);
732
+            $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
733
+
734
+            $owner = $path->getOwner();
735
+            $share->setShareOwner($owner->getUID());
736
+        }
737
+
738
+        if ($data['expiration'] !== null) {
739
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
740
+            if ($expiration !== false) {
741
+                $share->setExpirationDate($expiration);
742
+            }
743
+        }
744
+
745
+        $share->setNodeId((int)$data['file_source']);
746
+        $share->setNodeType($data['item_type']);
747
+
748
+        $share->setProviderId($this->identifier());
749
+
750
+        return $share;
751
+    }
752
+
753
+    /**
754
+     * Get the node with file $id for $user
755
+     *
756
+     * @param string $userId
757
+     * @param int $id
758
+     * @return \OCP\Files\File|\OCP\Files\Folder
759
+     * @throws InvalidShare
760
+     */
761
+    private function getNode($userId, $id) {
762
+        try {
763
+            $userFolder = $this->rootFolder->getUserFolder($userId);
764
+        } catch (NotFoundException $e) {
765
+            throw new InvalidShare();
766
+        }
767
+
768
+        $nodes = $userFolder->getById($id);
769
+
770
+        if (empty($nodes)) {
771
+            throw new InvalidShare();
772
+        }
773
+
774
+        return $nodes[0];
775
+    }
776
+
777
+    /**
778
+     * A user is deleted from the system
779
+     * So clean up the relevant shares.
780
+     *
781
+     * @param string $uid
782
+     * @param int $shareType
783
+     */
784
+    public function userDeleted($uid, $shareType) {
785
+        $qb = $this->dbConnection->getQueryBuilder();
786
+
787
+        $qb->delete('share')
788
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
789
+            ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
790
+            ->execute();
791
+    }
792
+
793
+    /**
794
+     * This provider does not support group shares
795
+     *
796
+     * @param string $gid
797
+     */
798
+    public function groupDeleted($gid) {
799
+        return;
800
+    }
801
+
802
+    /**
803
+     * This provider does not support group shares
804
+     *
805
+     * @param string $uid
806
+     * @param string $gid
807
+     */
808
+    public function userDeletedFromGroup($uid, $gid) {
809
+        return;
810
+    }
811
+
812
+    /**
813
+     * get database row of a give share
814
+     *
815
+     * @param $id
816
+     * @return array
817
+     * @throws ShareNotFound
818
+     */
819
+    protected function getRawShare($id) {
820
+
821
+        // Now fetch the inserted share and create a complete share object
822
+        $qb = $this->dbConnection->getQueryBuilder();
823
+        $qb->select('*')
824
+            ->from('share')
825
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
826
+
827
+        $cursor = $qb->execute();
828
+        $data = $cursor->fetch();
829
+        $cursor->closeCursor();
830
+
831
+        if ($data === false) {
832
+            throw new ShareNotFound;
833
+        }
834
+
835
+        return $data;
836
+    }
837
+
838
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
839
+        $qb = $this->dbConnection->getQueryBuilder();
840
+        $qb->select('*')
841
+            ->from('share', 's')
842
+            ->andWhere($qb->expr()->orX(
843
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
844
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
845
+            ))
846
+            ->andWhere(
847
+                $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
848
+            );
849
+
850
+        /**
851
+         * Reshares for this user are shares where they are the owner.
852
+         */
853
+        if ($reshares === false) {
854
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
855
+        } else {
856
+            $qb->andWhere(
857
+                $qb->expr()->orX(
858
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
859
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
860
+                )
861
+            );
862
+        }
863
+
864
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
865
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
866
+
867
+        $qb->orderBy('id');
868
+
869
+        $cursor = $qb->execute();
870
+        $shares = [];
871
+        while ($data = $cursor->fetch()) {
872
+            $shares[$data['fileid']][] = $this->createShareObject($data);
873
+        }
874
+        $cursor->closeCursor();
875
+
876
+        return $shares;
877
+    }
878
+
879
+    /**
880
+     * @inheritdoc
881
+     */
882
+    public function getAccessList($nodes, $currentAccess) {
883
+        $ids = [];
884
+        foreach ($nodes as $node) {
885
+            $ids[] = $node->getId();
886
+        }
887
+
888
+        $qb = $this->dbConnection->getQueryBuilder();
889
+        $qb->select('share_with')
890
+            ->from('share')
891
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
892
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
893
+            ->andWhere($qb->expr()->orX(
894
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
895
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
896
+            ))
897
+            ->setMaxResults(1);
898
+        $cursor = $qb->execute();
899
+
900
+        $mail = $cursor->fetch() !== false;
901
+        $cursor->closeCursor();
902
+
903
+        return ['public' => $mail];
904
+    }
905 905
 
906 906
 }
Please login to merge, or discard this patch.
lib/private/Mail/EMailTemplate.php 1 patch
Indentation   +234 added lines, -234 removed lines patch added patch discarded remove patch
@@ -39,25 +39,25 @@  discard block
 block discarded – undo
39 39
  * @package OC\Mail
40 40
  */
41 41
 class EMailTemplate implements IEMailTemplate {
42
-	/** @var Defaults */
43
-	protected $themingDefaults;
44
-	/** @var IURLGenerator */
45
-	protected $urlGenerator;
46
-	/** @var IL10N */
47
-	protected $l10n;
48
-
49
-	/** @var string */
50
-	protected $htmlBody = '';
51
-	/** @var string */
52
-	protected $plainBody = '';
53
-	/** @var bool indicated if the footer is added */
54
-	protected $headerAdded = false;
55
-	/** @var bool indicated if the body is already opened */
56
-	protected $bodyOpened = false;
57
-	/** @var bool indicated if the footer is added */
58
-	protected $footerAdded = false;
59
-
60
-	protected $head = <<<EOF
42
+    /** @var Defaults */
43
+    protected $themingDefaults;
44
+    /** @var IURLGenerator */
45
+    protected $urlGenerator;
46
+    /** @var IL10N */
47
+    protected $l10n;
48
+
49
+    /** @var string */
50
+    protected $htmlBody = '';
51
+    /** @var string */
52
+    protected $plainBody = '';
53
+    /** @var bool indicated if the footer is added */
54
+    protected $headerAdded = false;
55
+    /** @var bool indicated if the body is already opened */
56
+    protected $bodyOpened = false;
57
+    /** @var bool indicated if the footer is added */
58
+    protected $footerAdded = false;
59
+
60
+    protected $head = <<<EOF
61 61
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
62 62
 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en" style="-webkit-font-smoothing:antialiased;background:#f3f3f3!important">
63 63
 <head>
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
 				<center data-parsed="" style="min-width:580px;width:100%">
76 76
 EOF;
77 77
 
78
-	protected $tail = <<<EOF
78
+    protected $tail = <<<EOF
79 79
 					</center>
80 80
 				</td>
81 81
 			</tr>
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 </html>
87 87
 EOF;
88 88
 
89
-	protected $header = <<<EOF
89
+    protected $header = <<<EOF
90 90
 <table align="center" class="wrapper header float-center" style="Margin:0 auto;background:#8a8a8a;background-color:%s;border-collapse:collapse;border-spacing:0;float:none;margin:0 auto;padding:0;text-align:center;vertical-align:top;width:100%%">
91 91
 	<tr style="padding:0;text-align:left;vertical-align:top">
92 92
 		<td class="wrapper-inner" style="-moz-hyphens:auto;-webkit-hyphens:auto;Margin:0;border-collapse:collapse!important;color:#0a0a0a;font-family:Lucida Grande,Geneva,Verdana,sans-serif;font-size:16px;font-weight:400;hyphens:auto;line-height:1.3;margin:0;padding:20px;text-align:left;vertical-align:top;word-wrap:break-word">
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
 </table>
120 120
 EOF;
121 121
 
122
-	protected $heading = <<<EOF
122
+    protected $heading = <<<EOF
123 123
 <table align="center" class="container main-heading float-center" style="Margin:0 auto;background:0 0!important;border-collapse:collapse;border-spacing:0;float:none;margin:0 auto;padding:0;text-align:center;vertical-align:top;width:580px">
124 124
 	<tbody>
125 125
 	<tr style="padding:0;text-align:left;vertical-align:top">
@@ -138,7 +138,7 @@  discard block
 block discarded – undo
138 138
 </table>
139 139
 EOF;
140 140
 
141
-	protected $bodyBegin = <<<EOF
141
+    protected $bodyBegin = <<<EOF
142 142
 <table align="center" class="wrapper content float-center" style="Margin:0 auto;border-collapse:collapse;border-spacing:0;float:none;margin:0 auto;padding:0;text-align:center;vertical-align:top;width:100%">
143 143
 	<tr style="padding:0;text-align:left;vertical-align:top">
144 144
 		<td class="wrapper-inner" style="-moz-hyphens:auto;-webkit-hyphens:auto;Margin:0;border-collapse:collapse!important;color:#0a0a0a;font-family:Lucida Grande,Geneva,Verdana,sans-serif;font-size:16px;font-weight:400;hyphens:auto;line-height:1.3;margin:0;padding:0;text-align:left;vertical-align:top;word-wrap:break-word">
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 						</table>
156 156
 EOF;
157 157
 
158
-	protected $bodyText = <<<EOF
158
+    protected $bodyText = <<<EOF
159 159
 <table class="row description" style="border-collapse:collapse;border-spacing:0;display:table;padding:0;position:relative;text-align:left;vertical-align:top;width:100%%">
160 160
 	<tbody>
161 161
 	<tr style="padding:0;text-align:left;vertical-align:top">
@@ -174,7 +174,7 @@  discard block
 block discarded – undo
174 174
 </table>
175 175
 EOF;
176 176
 
177
-	protected $buttonGroup = <<<EOF
177
+    protected $buttonGroup = <<<EOF
178 178
 <table class="spacer" style="border-collapse:collapse;border-spacing:0;padding:0;text-align:left;vertical-align:top;width:100%%">
179 179
 	<tbody>
180 180
 	<tr style="padding:0;text-align:left;vertical-align:top">
@@ -227,7 +227,7 @@  discard block
 block discarded – undo
227 227
 </table>
228 228
 EOF;
229 229
 
230
-	protected $button = <<<EOF
230
+    protected $button = <<<EOF
231 231
 <table class="spacer" style="border-collapse:collapse;border-spacing:0;padding:0;text-align:left;vertical-align:top;width:100%%">
232 232
 	<tbody>
233 233
 	<tr style="padding:0;text-align:left;vertical-align:top">
@@ -267,7 +267,7 @@  discard block
 block discarded – undo
267 267
 </table>
268 268
 EOF;
269 269
 
270
-	protected $bodyEnd = <<<EOF
270
+    protected $bodyEnd = <<<EOF
271 271
 
272 272
 					</td>
273 273
 				</tr>
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
 </table>
279 279
 EOF;
280 280
 
281
-	protected $footer = <<<EOF
281
+    protected $footer = <<<EOF
282 282
 <table class="spacer float-center" style="Margin:0 auto;border-collapse:collapse;border-spacing:0;float:none;margin:0 auto;padding:0;text-align:center;vertical-align:top;width:100%%">
283 283
 	<tbody>
284 284
 	<tr style="padding:0;text-align:left;vertical-align:top">
@@ -304,210 +304,210 @@  discard block
 block discarded – undo
304 304
 </table>
305 305
 EOF;
306 306
 
307
-	/**
308
-	 * @param Defaults $themingDefaults
309
-	 * @param IURLGenerator $urlGenerator
310
-	 * @param IL10N $l10n
311
-	 */
312
-	public function __construct(Defaults $themingDefaults,
313
-								IURLGenerator $urlGenerator,
314
-								IL10N $l10n) {
315
-		$this->themingDefaults = $themingDefaults;
316
-		$this->urlGenerator = $urlGenerator;
317
-		$this->l10n = $l10n;
318
-		$this->htmlBody .= $this->head;
319
-	}
320
-
321
-	/**
322
-	 * Adds a header to the email
323
-	 */
324
-	public function addHeader() {
325
-		if ($this->headerAdded) {
326
-			return;
327
-		}
328
-		$this->headerAdded = true;
329
-
330
-		$logoUrl = $this->urlGenerator->getAbsoluteURL($this->themingDefaults->getLogo());
331
-		$this->htmlBody .= vsprintf($this->header, [$this->themingDefaults->getColorPrimary(), $logoUrl, $this->themingDefaults->getName()]);
332
-	}
333
-
334
-	/**
335
-	 * Adds a heading to the email
336
-	 *
337
-	 * @param string $title
338
-	 * @param string $plainTitle|bool Title that is used in the plain text email
339
-	 *   if empty the $title is used, if false none will be used
340
-	 */
341
-	public function addHeading($title, $plainTitle = '') {
342
-		if ($this->footerAdded) {
343
-			return;
344
-		}
345
-		if ($plainTitle === '') {
346
-			$plainTitle = $title;
347
-		}
348
-
349
-		$this->htmlBody .= vsprintf($this->heading, [htmlspecialchars($title)]);
350
-		if ($plainTitle !== false) {
351
-			$this->plainBody .= $plainTitle . PHP_EOL . PHP_EOL;
352
-		}
353
-	}
354
-
355
-	/**
356
-	 * Adds a paragraph to the body of the email
357
-	 *
358
-	 * @param string $text
359
-	 * @param string|bool $plainText Text that is used in the plain text email
360
-	 *   if empty the $text is used, if false none will be used
361
-	 */
362
-	public function addBodyText($text, $plainText = '') {
363
-		if ($this->footerAdded) {
364
-			return;
365
-		}
366
-		if ($plainText === '') {
367
-			$plainText = $text;
368
-		}
369
-
370
-		if (!$this->bodyOpened) {
371
-			$this->htmlBody .= $this->bodyBegin;
372
-			$this->bodyOpened = true;
373
-		}
374
-
375
-		$this->htmlBody .= vsprintf($this->bodyText, [htmlspecialchars($text)]);
376
-		if ($plainText !== false) {
377
-			$this->plainBody .= $plainText . PHP_EOL . PHP_EOL;
378
-		}
379
-	}
380
-
381
-	/**
382
-	 * Adds a button group of two buttons to the body of the email
383
-	 *
384
-	 * @param string $textLeft Text of left button
385
-	 * @param string $urlLeft URL of left button
386
-	 * @param string $textRight Text of right button
387
-	 * @param string $urlRight URL of right button
388
-	 * @param string $plainTextLeft Text of left button that is used in the plain text version - if unset the $textLeft is used
389
-	 * @param string $plainTextRight Text of right button that is used in the plain text version - if unset the $textRight is used
390
-	 */
391
-	public function addBodyButtonGroup($textLeft,
392
-									   $urlLeft,
393
-									   $textRight,
394
-									   $urlRight,
395
-									   $plainTextLeft = '',
396
-									   $plainTextRight = '') {
397
-		if ($this->footerAdded) {
398
-			return;
399
-		}
400
-		if ($plainTextLeft === '') {
401
-			$plainTextLeft = $textLeft;
402
-		}
403
-
404
-		if ($plainTextRight === '') {
405
-			$plainTextRight = $textRight;
406
-		}
407
-
408
-		if (!$this->bodyOpened) {
409
-			$this->htmlBody .= $this->bodyBegin;
410
-			$this->bodyOpened = true;
411
-		}
412
-
413
-		$color = $this->themingDefaults->getColorPrimary();
414
-
415
-		$this->htmlBody .= vsprintf($this->buttonGroup, [$color, $color, $urlLeft, $color, htmlspecialchars($textLeft), $urlRight, htmlspecialchars($textRight)]);
416
-		$this->plainBody .= $plainTextLeft . ': ' . $urlLeft . PHP_EOL;
417
-		$this->plainBody .= $plainTextRight . ': ' . $urlRight . PHP_EOL . PHP_EOL;
418
-
419
-	}
420
-
421
-	/**
422
-	 * Adds a button to the body of the email
423
-	 *
424
-	 * @param string $text Text of button
425
-	 * @param string $url URL of button
426
-	 * @param string $plainText Text of button in plain text version
427
-	 * 		if empty the $text is used, if false none will be used
428
-	 *
429
-	 * @since 12.0.0
430
-	 */
431
-	public function addBodyButton($text, $url, $plainText = '') {
432
-		if ($this->footerAdded) {
433
-			return;
434
-		}
435
-
436
-		if (!$this->bodyOpened) {
437
-			$this->htmlBody .= $this->bodyBegin;
438
-			$this->bodyOpened = true;
439
-		}
440
-
441
-		if ($plainText === '') {
442
-			$plainText = $text;
443
-		}
444
-
445
-		$color = $this->themingDefaults->getColorPrimary();
446
-		$this->htmlBody .= vsprintf($this->button, [$color, $color, $url, $color, htmlspecialchars($text)]);
447
-
448
-		if ($plainText !== false) {
449
-			$this->plainBody .= $plainText . ': ';
450
-		}
451
-
452
-		$this->plainBody .=  $url . PHP_EOL;
453
-
454
-	}
455
-
456
-	/**
457
-	 * Adds a logo and a text to the footer. <br> in the text will be replaced by new lines in the plain text email
458
-	 *
459
-	 * @param string $text If the text is empty the default "Name - Slogan<br>This is an automatically sent email" will be used
460
-	 */
461
-	public function addFooter($text = '') {
462
-		if($text === '') {
463
-			$text = $this->themingDefaults->getName() . ' - ' . $this->themingDefaults->getSlogan() . '<br>' . $this->l10n->t('This is an automatically sent email, please do not reply.');
464
-		}
465
-
466
-		if ($this->footerAdded) {
467
-			return;
468
-		}
469
-		$this->footerAdded = true;
470
-
471
-		if ($this->bodyOpened) {
472
-			$this->htmlBody .= $this->bodyEnd;
473
-			$this->bodyOpened = false;
474
-		}
475
-
476
-		$this->htmlBody .= vsprintf($this->footer, [$text]);
477
-		$this->htmlBody .= $this->tail;
478
-		$this->plainBody .= PHP_EOL . '-- ' . PHP_EOL;
479
-		$this->plainBody .= str_replace('<br>', PHP_EOL, $text);
480
-	}
481
-
482
-	/**
483
-	 * Returns the rendered HTML email as string
484
-	 *
485
-	 * @return string
486
-	 */
487
-	public function renderHtml() {
488
-		if (!$this->footerAdded) {
489
-			$this->footerAdded = true;
490
-			if ($this->bodyOpened) {
491
-				$this->htmlBody .= $this->bodyEnd;
492
-			}
493
-			$this->htmlBody .= $this->tail;
494
-		}
495
-		return $this->htmlBody;
496
-	}
497
-
498
-	/**
499
-	 * Returns the rendered plain text email as string
500
-	 *
501
-	 * @return string
502
-	 */
503
-	public function renderText() {
504
-		if (!$this->footerAdded) {
505
-			$this->footerAdded = true;
506
-			if ($this->bodyOpened) {
507
-				$this->htmlBody .= $this->bodyEnd;
508
-			}
509
-			$this->htmlBody .= $this->tail;
510
-		}
511
-		return $this->plainBody;
512
-	}
307
+    /**
308
+     * @param Defaults $themingDefaults
309
+     * @param IURLGenerator $urlGenerator
310
+     * @param IL10N $l10n
311
+     */
312
+    public function __construct(Defaults $themingDefaults,
313
+                                IURLGenerator $urlGenerator,
314
+                                IL10N $l10n) {
315
+        $this->themingDefaults = $themingDefaults;
316
+        $this->urlGenerator = $urlGenerator;
317
+        $this->l10n = $l10n;
318
+        $this->htmlBody .= $this->head;
319
+    }
320
+
321
+    /**
322
+     * Adds a header to the email
323
+     */
324
+    public function addHeader() {
325
+        if ($this->headerAdded) {
326
+            return;
327
+        }
328
+        $this->headerAdded = true;
329
+
330
+        $logoUrl = $this->urlGenerator->getAbsoluteURL($this->themingDefaults->getLogo());
331
+        $this->htmlBody .= vsprintf($this->header, [$this->themingDefaults->getColorPrimary(), $logoUrl, $this->themingDefaults->getName()]);
332
+    }
333
+
334
+    /**
335
+     * Adds a heading to the email
336
+     *
337
+     * @param string $title
338
+     * @param string $plainTitle|bool Title that is used in the plain text email
339
+     *   if empty the $title is used, if false none will be used
340
+     */
341
+    public function addHeading($title, $plainTitle = '') {
342
+        if ($this->footerAdded) {
343
+            return;
344
+        }
345
+        if ($plainTitle === '') {
346
+            $plainTitle = $title;
347
+        }
348
+
349
+        $this->htmlBody .= vsprintf($this->heading, [htmlspecialchars($title)]);
350
+        if ($plainTitle !== false) {
351
+            $this->plainBody .= $plainTitle . PHP_EOL . PHP_EOL;
352
+        }
353
+    }
354
+
355
+    /**
356
+     * Adds a paragraph to the body of the email
357
+     *
358
+     * @param string $text
359
+     * @param string|bool $plainText Text that is used in the plain text email
360
+     *   if empty the $text is used, if false none will be used
361
+     */
362
+    public function addBodyText($text, $plainText = '') {
363
+        if ($this->footerAdded) {
364
+            return;
365
+        }
366
+        if ($plainText === '') {
367
+            $plainText = $text;
368
+        }
369
+
370
+        if (!$this->bodyOpened) {
371
+            $this->htmlBody .= $this->bodyBegin;
372
+            $this->bodyOpened = true;
373
+        }
374
+
375
+        $this->htmlBody .= vsprintf($this->bodyText, [htmlspecialchars($text)]);
376
+        if ($plainText !== false) {
377
+            $this->plainBody .= $plainText . PHP_EOL . PHP_EOL;
378
+        }
379
+    }
380
+
381
+    /**
382
+     * Adds a button group of two buttons to the body of the email
383
+     *
384
+     * @param string $textLeft Text of left button
385
+     * @param string $urlLeft URL of left button
386
+     * @param string $textRight Text of right button
387
+     * @param string $urlRight URL of right button
388
+     * @param string $plainTextLeft Text of left button that is used in the plain text version - if unset the $textLeft is used
389
+     * @param string $plainTextRight Text of right button that is used in the plain text version - if unset the $textRight is used
390
+     */
391
+    public function addBodyButtonGroup($textLeft,
392
+                                        $urlLeft,
393
+                                        $textRight,
394
+                                        $urlRight,
395
+                                        $plainTextLeft = '',
396
+                                        $plainTextRight = '') {
397
+        if ($this->footerAdded) {
398
+            return;
399
+        }
400
+        if ($plainTextLeft === '') {
401
+            $plainTextLeft = $textLeft;
402
+        }
403
+
404
+        if ($plainTextRight === '') {
405
+            $plainTextRight = $textRight;
406
+        }
407
+
408
+        if (!$this->bodyOpened) {
409
+            $this->htmlBody .= $this->bodyBegin;
410
+            $this->bodyOpened = true;
411
+        }
412
+
413
+        $color = $this->themingDefaults->getColorPrimary();
414
+
415
+        $this->htmlBody .= vsprintf($this->buttonGroup, [$color, $color, $urlLeft, $color, htmlspecialchars($textLeft), $urlRight, htmlspecialchars($textRight)]);
416
+        $this->plainBody .= $plainTextLeft . ': ' . $urlLeft . PHP_EOL;
417
+        $this->plainBody .= $plainTextRight . ': ' . $urlRight . PHP_EOL . PHP_EOL;
418
+
419
+    }
420
+
421
+    /**
422
+     * Adds a button to the body of the email
423
+     *
424
+     * @param string $text Text of button
425
+     * @param string $url URL of button
426
+     * @param string $plainText Text of button in plain text version
427
+     * 		if empty the $text is used, if false none will be used
428
+     *
429
+     * @since 12.0.0
430
+     */
431
+    public function addBodyButton($text, $url, $plainText = '') {
432
+        if ($this->footerAdded) {
433
+            return;
434
+        }
435
+
436
+        if (!$this->bodyOpened) {
437
+            $this->htmlBody .= $this->bodyBegin;
438
+            $this->bodyOpened = true;
439
+        }
440
+
441
+        if ($plainText === '') {
442
+            $plainText = $text;
443
+        }
444
+
445
+        $color = $this->themingDefaults->getColorPrimary();
446
+        $this->htmlBody .= vsprintf($this->button, [$color, $color, $url, $color, htmlspecialchars($text)]);
447
+
448
+        if ($plainText !== false) {
449
+            $this->plainBody .= $plainText . ': ';
450
+        }
451
+
452
+        $this->plainBody .=  $url . PHP_EOL;
453
+
454
+    }
455
+
456
+    /**
457
+     * Adds a logo and a text to the footer. <br> in the text will be replaced by new lines in the plain text email
458
+     *
459
+     * @param string $text If the text is empty the default "Name - Slogan<br>This is an automatically sent email" will be used
460
+     */
461
+    public function addFooter($text = '') {
462
+        if($text === '') {
463
+            $text = $this->themingDefaults->getName() . ' - ' . $this->themingDefaults->getSlogan() . '<br>' . $this->l10n->t('This is an automatically sent email, please do not reply.');
464
+        }
465
+
466
+        if ($this->footerAdded) {
467
+            return;
468
+        }
469
+        $this->footerAdded = true;
470
+
471
+        if ($this->bodyOpened) {
472
+            $this->htmlBody .= $this->bodyEnd;
473
+            $this->bodyOpened = false;
474
+        }
475
+
476
+        $this->htmlBody .= vsprintf($this->footer, [$text]);
477
+        $this->htmlBody .= $this->tail;
478
+        $this->plainBody .= PHP_EOL . '-- ' . PHP_EOL;
479
+        $this->plainBody .= str_replace('<br>', PHP_EOL, $text);
480
+    }
481
+
482
+    /**
483
+     * Returns the rendered HTML email as string
484
+     *
485
+     * @return string
486
+     */
487
+    public function renderHtml() {
488
+        if (!$this->footerAdded) {
489
+            $this->footerAdded = true;
490
+            if ($this->bodyOpened) {
491
+                $this->htmlBody .= $this->bodyEnd;
492
+            }
493
+            $this->htmlBody .= $this->tail;
494
+        }
495
+        return $this->htmlBody;
496
+    }
497
+
498
+    /**
499
+     * Returns the rendered plain text email as string
500
+     *
501
+     * @return string
502
+     */
503
+    public function renderText() {
504
+        if (!$this->footerAdded) {
505
+            $this->footerAdded = true;
506
+            if ($this->bodyOpened) {
507
+                $this->htmlBody .= $this->bodyEnd;
508
+            }
509
+            $this->htmlBody .= $this->tail;
510
+        }
511
+        return $this->plainBody;
512
+    }
513 513
 }
Please login to merge, or discard this patch.
lib/public/Mail/IEMailTemplate.php 1 patch
Indentation   +74 added lines, -74 removed lines patch added patch discarded remove patch
@@ -51,85 +51,85 @@
 block discarded – undo
51 51
  * @since 12.0.0
52 52
  */
53 53
 interface IEMailTemplate {
54
-	/**
55
-	 * Adds a header to the email
56
-	 *
57
-	 * @since 12.0.0
58
-	 */
59
-	public function addHeader();
54
+    /**
55
+     * Adds a header to the email
56
+     *
57
+     * @since 12.0.0
58
+     */
59
+    public function addHeader();
60 60
 
61
-	/**
62
-	 * Adds a heading to the email
63
-	 *
64
-	 * @param string $title
65
-	 * @param string $plainTitle|bool Title that is used in the plain text email
66
-	 *   if empty the $title is used, if false none will be used
67
-	 *
68
-	 * @since 12.0.0
69
-	 */
70
-	public function addHeading($title, $plainTitle = '');
61
+    /**
62
+     * Adds a heading to the email
63
+     *
64
+     * @param string $title
65
+     * @param string $plainTitle|bool Title that is used in the plain text email
66
+     *   if empty the $title is used, if false none will be used
67
+     *
68
+     * @since 12.0.0
69
+     */
70
+    public function addHeading($title, $plainTitle = '');
71 71
 
72
-	/**
73
-	 * Adds a paragraph to the body of the email
74
-	 *
75
-	 * @param string $text
76
-	 * @param string|bool $plainText Text that is used in the plain text email
77
-	 *   if empty the $text is used, if false none will be used
78
-	 *
79
-	 * @since 12.0.0
80
-	 */
81
-	public function addBodyText($text, $plainText = '');
72
+    /**
73
+     * Adds a paragraph to the body of the email
74
+     *
75
+     * @param string $text
76
+     * @param string|bool $plainText Text that is used in the plain text email
77
+     *   if empty the $text is used, if false none will be used
78
+     *
79
+     * @since 12.0.0
80
+     */
81
+    public function addBodyText($text, $plainText = '');
82 82
 
83
-	/**
84
-	 * Adds a button group of two buttons to the body of the email
85
-	 *
86
-	 * @param string $textLeft Text of left button
87
-	 * @param string $urlLeft URL of left button
88
-	 * @param string $textRight Text of right button
89
-	 * @param string $urlRight URL of right button
90
-	 * @param string $plainTextLeft Text of left button that is used in the plain text version - if empty the $textLeft is used
91
-	 * @param string $plainTextRight Text of right button that is used in the plain text version - if empty the $textRight is used
92
-	 *
93
-	 * @since 12.0.0
94
-	 */
95
-	public function addBodyButtonGroup($textLeft, $urlLeft, $textRight, $urlRight, $plainTextLeft = '', $plainTextRight = '');
83
+    /**
84
+     * Adds a button group of two buttons to the body of the email
85
+     *
86
+     * @param string $textLeft Text of left button
87
+     * @param string $urlLeft URL of left button
88
+     * @param string $textRight Text of right button
89
+     * @param string $urlRight URL of right button
90
+     * @param string $plainTextLeft Text of left button that is used in the plain text version - if empty the $textLeft is used
91
+     * @param string $plainTextRight Text of right button that is used in the plain text version - if empty the $textRight is used
92
+     *
93
+     * @since 12.0.0
94
+     */
95
+    public function addBodyButtonGroup($textLeft, $urlLeft, $textRight, $urlRight, $plainTextLeft = '', $plainTextRight = '');
96 96
 
97
-	/**
98
-	 * Adds a button to the body of the email
99
-	 *
100
-	 * @param string $text Text of button
101
-	 * @param string $url URL of button
102
-	 * @param string $plainText Text of button in plain text version
103
-	 * 		if empty the $text is used, if false none will be used
104
-	 *
105
-	 * @since 12.0.0
106
-	 */
107
-	public function addBodyButton($text, $url, $plainText = '');
97
+    /**
98
+     * Adds a button to the body of the email
99
+     *
100
+     * @param string $text Text of button
101
+     * @param string $url URL of button
102
+     * @param string $plainText Text of button in plain text version
103
+     * 		if empty the $text is used, if false none will be used
104
+     *
105
+     * @since 12.0.0
106
+     */
107
+    public function addBodyButton($text, $url, $plainText = '');
108 108
 
109
-	/**
110
-	 * Adds a logo and a text to the footer. <br> in the text will be replaced by new lines in the plain text email
111
-	 *
112
-	 * @param string $text If the text is empty the default "Name - Slogan<br>This is an automatically sent email" will be used
113
-	 *
114
-	 * @since 12.0.0
115
-	 */
116
-	public function addFooter($text = '');
109
+    /**
110
+     * Adds a logo and a text to the footer. <br> in the text will be replaced by new lines in the plain text email
111
+     *
112
+     * @param string $text If the text is empty the default "Name - Slogan<br>This is an automatically sent email" will be used
113
+     *
114
+     * @since 12.0.0
115
+     */
116
+    public function addFooter($text = '');
117 117
 
118
-	/**
119
-	 * Returns the rendered HTML email as string
120
-	 *
121
-	 * @return string
122
-	 *
123
-	 * @since 12.0.0
124
-	 */
125
-	public function renderHtml();
118
+    /**
119
+     * Returns the rendered HTML email as string
120
+     *
121
+     * @return string
122
+     *
123
+     * @since 12.0.0
124
+     */
125
+    public function renderHtml();
126 126
 
127
-	/**
128
-	 * Returns the rendered plain text email as string
129
-	 *
130
-	 * @return string
131
-	 *
132
-	 * @since 12.0.0
133
-	 */
134
-	public function renderText();
127
+    /**
128
+     * Returns the rendered plain text email as string
129
+     *
130
+     * @return string
131
+     *
132
+     * @since 12.0.0
133
+     */
134
+    public function renderText();
135 135
 }
Please login to merge, or discard this patch.
core/Controller/LostController.php 1 patch
Indentation   +282 added lines, -282 removed lines patch added patch discarded remove patch
@@ -56,286 +56,286 @@
 block discarded – undo
56 56
  */
57 57
 class LostController extends Controller {
58 58
 
59
-	/** @var IURLGenerator */
60
-	protected $urlGenerator;
61
-	/** @var IUserManager */
62
-	protected $userManager;
63
-	/** @var Defaults */
64
-	protected $defaults;
65
-	/** @var IL10N */
66
-	protected $l10n;
67
-	/** @var string */
68
-	protected $from;
69
-	/** @var IManager */
70
-	protected $encryptionManager;
71
-	/** @var IConfig */
72
-	protected $config;
73
-	/** @var ISecureRandom */
74
-	protected $secureRandom;
75
-	/** @var IMailer */
76
-	protected $mailer;
77
-	/** @var ITimeFactory */
78
-	protected $timeFactory;
79
-	/** @var ICrypto */
80
-	protected $crypto;
81
-
82
-	/**
83
-	 * @param string $appName
84
-	 * @param IRequest $request
85
-	 * @param IURLGenerator $urlGenerator
86
-	 * @param IUserManager $userManager
87
-	 * @param Defaults $defaults
88
-	 * @param IL10N $l10n
89
-	 * @param IConfig $config
90
-	 * @param ISecureRandom $secureRandom
91
-	 * @param string $defaultMailAddress
92
-	 * @param IManager $encryptionManager
93
-	 * @param IMailer $mailer
94
-	 * @param ITimeFactory $timeFactory
95
-	 * @param ICrypto $crypto
96
-	 */
97
-	public function __construct($appName,
98
-								IRequest $request,
99
-								IURLGenerator $urlGenerator,
100
-								IUserManager $userManager,
101
-								Defaults $defaults,
102
-								IL10N $l10n,
103
-								IConfig $config,
104
-								ISecureRandom $secureRandom,
105
-								$defaultMailAddress,
106
-								IManager $encryptionManager,
107
-								IMailer $mailer,
108
-								ITimeFactory $timeFactory,
109
-								ICrypto $crypto) {
110
-		parent::__construct($appName, $request);
111
-		$this->urlGenerator = $urlGenerator;
112
-		$this->userManager = $userManager;
113
-		$this->defaults = $defaults;
114
-		$this->l10n = $l10n;
115
-		$this->secureRandom = $secureRandom;
116
-		$this->from = $defaultMailAddress;
117
-		$this->encryptionManager = $encryptionManager;
118
-		$this->config = $config;
119
-		$this->mailer = $mailer;
120
-		$this->timeFactory = $timeFactory;
121
-		$this->crypto = $crypto;
122
-	}
123
-
124
-	/**
125
-	 * Someone wants to reset their password:
126
-	 *
127
-	 * @PublicPage
128
-	 * @NoCSRFRequired
129
-	 *
130
-	 * @param string $token
131
-	 * @param string $userId
132
-	 * @return TemplateResponse
133
-	 */
134
-	public function resetform($token, $userId) {
135
-		try {
136
-			$this->checkPasswordResetToken($token, $userId);
137
-		} catch (\Exception $e) {
138
-			return new TemplateResponse(
139
-				'core', 'error', [
140
-					"errors" => array(array("error" => $e->getMessage()))
141
-				],
142
-				'guest'
143
-			);
144
-		}
145
-
146
-		return new TemplateResponse(
147
-			'core',
148
-			'lostpassword/resetpassword',
149
-			array(
150
-				'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
151
-			),
152
-			'guest'
153
-		);
154
-	}
155
-
156
-	/**
157
-	 * @param string $token
158
-	 * @param string $userId
159
-	 * @throws \Exception
160
-	 */
161
-	protected function checkPasswordResetToken($token, $userId) {
162
-		$user = $this->userManager->get($userId);
163
-		if($user === null) {
164
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
165
-		}
166
-
167
-		try {
168
-			$encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
169
-			$mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
170
-			$decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
171
-		} catch (\Exception $e) {
172
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
173
-		}
174
-
175
-		$splittedToken = explode(':', $decryptedToken);
176
-		if(count($splittedToken) !== 2) {
177
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
178
-		}
179
-
180
-		if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
181
-			$user->getLastLogin() > $splittedToken[0]) {
182
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
183
-		}
184
-
185
-		if (!hash_equals($splittedToken[1], $token)) {
186
-			throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
187
-		}
188
-	}
189
-
190
-	/**
191
-	 * @param $message
192
-	 * @param array $additional
193
-	 * @return array
194
-	 */
195
-	private function error($message, array $additional=array()) {
196
-		return array_merge(array('status' => 'error', 'msg' => $message), $additional);
197
-	}
198
-
199
-	/**
200
-	 * @return array
201
-	 */
202
-	private function success() {
203
-		return array('status'=>'success');
204
-	}
205
-
206
-	/**
207
-	 * @PublicPage
208
-	 * @BruteForceProtection(action=passwordResetEmail)
209
-	 *
210
-	 * @param string $user
211
-	 * @return JSONResponse
212
-	 */
213
-	public function email($user){
214
-		// FIXME: use HTTP error codes
215
-		try {
216
-			$this->sendEmail($user);
217
-		} catch (\Exception $e){
218
-			$response = new JSONResponse($this->error($e->getMessage()));
219
-			$response->throttle();
220
-			return $response;
221
-		}
222
-
223
-		$response = new JSONResponse($this->success());
224
-		$response->throttle();
225
-		return $response;
226
-	}
227
-
228
-	/**
229
-	 * @PublicPage
230
-	 * @param string $token
231
-	 * @param string $userId
232
-	 * @param string $password
233
-	 * @param boolean $proceed
234
-	 * @return array
235
-	 */
236
-	public function setPassword($token, $userId, $password, $proceed) {
237
-		if ($this->encryptionManager->isEnabled() && !$proceed) {
238
-			return $this->error('', array('encryption' => true));
239
-		}
240
-
241
-		try {
242
-			$this->checkPasswordResetToken($token, $userId);
243
-			$user = $this->userManager->get($userId);
244
-
245
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', array('uid' => $userId, 'password' => $password));
246
-
247
-			if (!$user->setPassword($password)) {
248
-				throw new \Exception();
249
-			}
250
-
251
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
252
-
253
-			$this->config->deleteUserValue($userId, 'core', 'lostpassword');
254
-			@\OC_User::unsetMagicInCookie();
255
-		} catch (\Exception $e){
256
-			return $this->error($e->getMessage());
257
-		}
258
-
259
-		return $this->success();
260
-	}
261
-
262
-	/**
263
-	 * @param string $input
264
-	 * @throws \Exception
265
-	 */
266
-	protected function sendEmail($input) {
267
-		$user = $this->findUserByIdOrMail($input);
268
-		$email = $user->getEMailAddress();
269
-
270
-		if (empty($email)) {
271
-			throw new \Exception(
272
-				$this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
273
-			);
274
-		}
275
-
276
-		// Generate the token. It is stored encrypted in the database with the
277
-		// secret being the users' email address appended with the system secret.
278
-		// This makes the token automatically invalidate once the user changes
279
-		// their email address.
280
-		$token = $this->secureRandom->generate(
281
-			21,
282
-			ISecureRandom::CHAR_DIGITS.
283
-			ISecureRandom::CHAR_LOWER.
284
-			ISecureRandom::CHAR_UPPER
285
-		);
286
-		$tokenValue = $this->timeFactory->getTime() .':'. $token;
287
-		$encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
288
-		$this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
289
-
290
-		$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
291
-
292
-		$emailTemplate = $this->mailer->createEMailTemplate();
293
-
294
-		$emailTemplate->addHeader();
295
-		$emailTemplate->addHeading($this->l10n->t('Password reset'));
296
-
297
-		$emailTemplate->addBodyText(
298
-			$this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.'),
299
-			$this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
300
-		);
301
-
302
-		$emailTemplate->addBodyButton(
303
-			$this->l10n->t('Reset your password'),
304
-			$link,
305
-			false
306
-		);
307
-		$emailTemplate->addFooter();
308
-
309
-		try {
310
-			$message = $this->mailer->createMessage();
311
-			$message->setTo([$email => $user->getUID()]);
312
-			$message->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
313
-			$message->setPlainBody($emailTemplate->renderText());
314
-			$message->setHtmlBody($emailTemplate->renderHtml());
315
-			$message->setFrom([$this->from => $this->defaults->getName()]);
316
-			$this->mailer->send($message);
317
-		} catch (\Exception $e) {
318
-			throw new \Exception($this->l10n->t(
319
-				'Couldn\'t send reset email. Please contact your administrator.'
320
-			));
321
-		}
322
-	}
323
-
324
-	/**
325
-	 * @param string $input
326
-	 * @return IUser
327
-	 * @throws \Exception
328
-	 */
329
-	protected function findUserByIdOrMail($input) {
330
-		$user = $this->userManager->get($input);
331
-		if ($user instanceof IUser) {
332
-			return $user;
333
-		}
334
-		$users = $this->userManager->getByEmail($input);
335
-		if (count($users) === 1) {
336
-			return $users[0];
337
-		}
338
-
339
-		throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
340
-	}
59
+    /** @var IURLGenerator */
60
+    protected $urlGenerator;
61
+    /** @var IUserManager */
62
+    protected $userManager;
63
+    /** @var Defaults */
64
+    protected $defaults;
65
+    /** @var IL10N */
66
+    protected $l10n;
67
+    /** @var string */
68
+    protected $from;
69
+    /** @var IManager */
70
+    protected $encryptionManager;
71
+    /** @var IConfig */
72
+    protected $config;
73
+    /** @var ISecureRandom */
74
+    protected $secureRandom;
75
+    /** @var IMailer */
76
+    protected $mailer;
77
+    /** @var ITimeFactory */
78
+    protected $timeFactory;
79
+    /** @var ICrypto */
80
+    protected $crypto;
81
+
82
+    /**
83
+     * @param string $appName
84
+     * @param IRequest $request
85
+     * @param IURLGenerator $urlGenerator
86
+     * @param IUserManager $userManager
87
+     * @param Defaults $defaults
88
+     * @param IL10N $l10n
89
+     * @param IConfig $config
90
+     * @param ISecureRandom $secureRandom
91
+     * @param string $defaultMailAddress
92
+     * @param IManager $encryptionManager
93
+     * @param IMailer $mailer
94
+     * @param ITimeFactory $timeFactory
95
+     * @param ICrypto $crypto
96
+     */
97
+    public function __construct($appName,
98
+                                IRequest $request,
99
+                                IURLGenerator $urlGenerator,
100
+                                IUserManager $userManager,
101
+                                Defaults $defaults,
102
+                                IL10N $l10n,
103
+                                IConfig $config,
104
+                                ISecureRandom $secureRandom,
105
+                                $defaultMailAddress,
106
+                                IManager $encryptionManager,
107
+                                IMailer $mailer,
108
+                                ITimeFactory $timeFactory,
109
+                                ICrypto $crypto) {
110
+        parent::__construct($appName, $request);
111
+        $this->urlGenerator = $urlGenerator;
112
+        $this->userManager = $userManager;
113
+        $this->defaults = $defaults;
114
+        $this->l10n = $l10n;
115
+        $this->secureRandom = $secureRandom;
116
+        $this->from = $defaultMailAddress;
117
+        $this->encryptionManager = $encryptionManager;
118
+        $this->config = $config;
119
+        $this->mailer = $mailer;
120
+        $this->timeFactory = $timeFactory;
121
+        $this->crypto = $crypto;
122
+    }
123
+
124
+    /**
125
+     * Someone wants to reset their password:
126
+     *
127
+     * @PublicPage
128
+     * @NoCSRFRequired
129
+     *
130
+     * @param string $token
131
+     * @param string $userId
132
+     * @return TemplateResponse
133
+     */
134
+    public function resetform($token, $userId) {
135
+        try {
136
+            $this->checkPasswordResetToken($token, $userId);
137
+        } catch (\Exception $e) {
138
+            return new TemplateResponse(
139
+                'core', 'error', [
140
+                    "errors" => array(array("error" => $e->getMessage()))
141
+                ],
142
+                'guest'
143
+            );
144
+        }
145
+
146
+        return new TemplateResponse(
147
+            'core',
148
+            'lostpassword/resetpassword',
149
+            array(
150
+                'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
151
+            ),
152
+            'guest'
153
+        );
154
+    }
155
+
156
+    /**
157
+     * @param string $token
158
+     * @param string $userId
159
+     * @throws \Exception
160
+     */
161
+    protected function checkPasswordResetToken($token, $userId) {
162
+        $user = $this->userManager->get($userId);
163
+        if($user === null) {
164
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
165
+        }
166
+
167
+        try {
168
+            $encryptedToken = $this->config->getUserValue($userId, 'core', 'lostpassword', null);
169
+            $mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
170
+            $decryptedToken = $this->crypto->decrypt($encryptedToken, $mailAddress.$this->config->getSystemValue('secret'));
171
+        } catch (\Exception $e) {
172
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
173
+        }
174
+
175
+        $splittedToken = explode(':', $decryptedToken);
176
+        if(count($splittedToken) !== 2) {
177
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
178
+        }
179
+
180
+        if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
181
+            $user->getLastLogin() > $splittedToken[0]) {
182
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
183
+        }
184
+
185
+        if (!hash_equals($splittedToken[1], $token)) {
186
+            throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
187
+        }
188
+    }
189
+
190
+    /**
191
+     * @param $message
192
+     * @param array $additional
193
+     * @return array
194
+     */
195
+    private function error($message, array $additional=array()) {
196
+        return array_merge(array('status' => 'error', 'msg' => $message), $additional);
197
+    }
198
+
199
+    /**
200
+     * @return array
201
+     */
202
+    private function success() {
203
+        return array('status'=>'success');
204
+    }
205
+
206
+    /**
207
+     * @PublicPage
208
+     * @BruteForceProtection(action=passwordResetEmail)
209
+     *
210
+     * @param string $user
211
+     * @return JSONResponse
212
+     */
213
+    public function email($user){
214
+        // FIXME: use HTTP error codes
215
+        try {
216
+            $this->sendEmail($user);
217
+        } catch (\Exception $e){
218
+            $response = new JSONResponse($this->error($e->getMessage()));
219
+            $response->throttle();
220
+            return $response;
221
+        }
222
+
223
+        $response = new JSONResponse($this->success());
224
+        $response->throttle();
225
+        return $response;
226
+    }
227
+
228
+    /**
229
+     * @PublicPage
230
+     * @param string $token
231
+     * @param string $userId
232
+     * @param string $password
233
+     * @param boolean $proceed
234
+     * @return array
235
+     */
236
+    public function setPassword($token, $userId, $password, $proceed) {
237
+        if ($this->encryptionManager->isEnabled() && !$proceed) {
238
+            return $this->error('', array('encryption' => true));
239
+        }
240
+
241
+        try {
242
+            $this->checkPasswordResetToken($token, $userId);
243
+            $user = $this->userManager->get($userId);
244
+
245
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'pre_passwordReset', array('uid' => $userId, 'password' => $password));
246
+
247
+            if (!$user->setPassword($password)) {
248
+                throw new \Exception();
249
+            }
250
+
251
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
252
+
253
+            $this->config->deleteUserValue($userId, 'core', 'lostpassword');
254
+            @\OC_User::unsetMagicInCookie();
255
+        } catch (\Exception $e){
256
+            return $this->error($e->getMessage());
257
+        }
258
+
259
+        return $this->success();
260
+    }
261
+
262
+    /**
263
+     * @param string $input
264
+     * @throws \Exception
265
+     */
266
+    protected function sendEmail($input) {
267
+        $user = $this->findUserByIdOrMail($input);
268
+        $email = $user->getEMailAddress();
269
+
270
+        if (empty($email)) {
271
+            throw new \Exception(
272
+                $this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
273
+            );
274
+        }
275
+
276
+        // Generate the token. It is stored encrypted in the database with the
277
+        // secret being the users' email address appended with the system secret.
278
+        // This makes the token automatically invalidate once the user changes
279
+        // their email address.
280
+        $token = $this->secureRandom->generate(
281
+            21,
282
+            ISecureRandom::CHAR_DIGITS.
283
+            ISecureRandom::CHAR_LOWER.
284
+            ISecureRandom::CHAR_UPPER
285
+        );
286
+        $tokenValue = $this->timeFactory->getTime() .':'. $token;
287
+        $encryptedValue = $this->crypto->encrypt($tokenValue, $email . $this->config->getSystemValue('secret'));
288
+        $this->config->setUserValue($user->getUID(), 'core', 'lostpassword', $encryptedValue);
289
+
290
+        $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user->getUID(), 'token' => $token));
291
+
292
+        $emailTemplate = $this->mailer->createEMailTemplate();
293
+
294
+        $emailTemplate->addHeader();
295
+        $emailTemplate->addHeading($this->l10n->t('Password reset'));
296
+
297
+        $emailTemplate->addBodyText(
298
+            $this->l10n->t('Click the following button to reset your password. If you have not requested the password reset, then ignore this email.'),
299
+            $this->l10n->t('Click the following link to reset your password. If you have not requested the password reset, then ignore this email.')
300
+        );
301
+
302
+        $emailTemplate->addBodyButton(
303
+            $this->l10n->t('Reset your password'),
304
+            $link,
305
+            false
306
+        );
307
+        $emailTemplate->addFooter();
308
+
309
+        try {
310
+            $message = $this->mailer->createMessage();
311
+            $message->setTo([$email => $user->getUID()]);
312
+            $message->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
313
+            $message->setPlainBody($emailTemplate->renderText());
314
+            $message->setHtmlBody($emailTemplate->renderHtml());
315
+            $message->setFrom([$this->from => $this->defaults->getName()]);
316
+            $this->mailer->send($message);
317
+        } catch (\Exception $e) {
318
+            throw new \Exception($this->l10n->t(
319
+                'Couldn\'t send reset email. Please contact your administrator.'
320
+            ));
321
+        }
322
+    }
323
+
324
+    /**
325
+     * @param string $input
326
+     * @return IUser
327
+     * @throws \Exception
328
+     */
329
+    protected function findUserByIdOrMail($input) {
330
+        $user = $this->userManager->get($input);
331
+        if ($user instanceof IUser) {
332
+            return $user;
333
+        }
334
+        $users = $this->userManager->getByEmail($input);
335
+        if (count($users) === 1) {
336
+            return $users[0];
337
+        }
338
+
339
+        throw new \InvalidArgumentException($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
340
+    }
341 341
 }
Please login to merge, or discard this patch.