Completed
Push — master ( ec29fe...2e5711 )
by Torben
09:02 queued 07:11
created

NotificationService::sendUserMessage()   B

Complexity

Conditions 6
Paths 3

Size

Total Lines 27
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 27
ccs 19
cts 19
cp 1
rs 8.439
c 1
b 0
f 0
cc 6
eloc 19
nc 3
nop 5
crap 6
1
<?php
2
namespace DERHANSEN\SfEventMgt\Service;
3
4
/*
5
 * This file is part of the TYPO3 CMS project.
6
 *
7
 * It is free software; you can redistribute it and/or modify it under
8
 * the terms of the GNU General Public License, either version 2
9
 * of the License, or any later version.
10
 *
11
 * For the full copyright and license information, please read the
12
 * LICENSE.txt file that was distributed with this source code.
13
 *
14
 * The TYPO3 project - inspiring people to share!
15
 */
16
17
use DERHANSEN\SfEventMgt\Utility\MessageType;
18
use DERHANSEN\SfEventMgt\Utility\MessageRecipient;
19
use \TYPO3\CMS\Core\Utility\GeneralUtility;
20
21
/**
22
 * NotificationService
23
 *
24
 * @author Torben Hansen <[email protected]>
25
 */
26
class NotificationService
27
{
28
29
    /**
30
     * The object manager
31
     *
32
     * @var \TYPO3\CMS\Extbase\Object\ObjectManager
33
     * @inject
34
     */
35
    protected $objectManager;
36
37
    /**
38
     * Registration repository
39
     *
40
     * @var \DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository
41
     * @inject
42
     */
43
    protected $registrationRepository = null;
44
45
    /**
46
     * Email Service
47
     *
48
     * @var \DERHANSEN\SfEventMgt\Service\EmailService
49
     * @inject
50
     */
51
    protected $emailService;
52
53
    /**
54
     * Hash Service
55
     *
56
     * @var \TYPO3\CMS\Extbase\Security\Cryptography\HashService
57
     * @inject
58
     */
59
    protected $hashService;
60
61
    /**
62
     * FluidStandaloneService
63
     *
64
     * @var \DERHANSEN\SfEventMgt\Service\FluidStandaloneService
65
     * @inject
66
     */
67
    protected $fluidStandaloneService;
68
69
    /**
70
     * CustomNotificationLogRepository
71
     *
72
     * @var \DERHANSEN\SfEventMgt\Domain\Repository\CustomNotificationLogRepository
73
     * @inject
74
     */
75
    protected $customNotificationLogRepository = null;
76
77
    /**
78
     * AttachmentService
79
     *
80
     * @var \DERHANSEN\SfEventMgt\Service\Notification\AttachmentService
81
     * @inject
82
     */
83
    protected $attachmentService;
84
85
    /**
86
     * Sends a custom notification defined by the given customNotification key
87
     * to all confirmed users of the event
88
     *
89
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
90
     * @param string $customNotification CustomNotification
91
     * @param array $settings Settings
92
     *
93
     * @return int Number of notifications sent
94
     */
95 4
    public function sendCustomNotification($event, $customNotification, $settings)
96
    {
97 4
        if ($this->cantSendCustomNotification($event, $settings, $customNotification)) {
98 1
            return 0;
99
        }
100 3
        $count = 0;
101
102 3
        $constraints = $settings['notification']['customNotifications'][$customNotification]['constraints'];
103 3
        $registrations = $this->registrationRepository->findNotificationRegistrations($event, $constraints);
104 3
        foreach ($registrations as $registration) {
105
            /** @var \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration */
106 3
            if ($registration->isConfirmed() && !$registration->isIgnoreNotifications()) {
107 1
                $result = $this->sendUserMessage(
108 1
                    $event,
109 1
                    $registration,
110 1
                    $settings,
111 1
                    MessageType::CUSTOM_NOTIFICATION,
112
                    $customNotification
113 1
                );
114 1
                if ($result) {
115 1
                    $count += 1;
116 1
                }
117 1
            }
118 3
        }
119 3
        return $count;
120
    }
121
122
    /**
123
     * Returns true if conditions are not met to send a custom notification
124
     *
125
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event
126
     * @param array $settings
127
     * @param string $customNotification
128
     *
129
     * @return bool
130
     */
131 4
    protected function cantSendCustomNotification($event, $settings, $customNotification)
132
    {
133 4
        return is_null($event) || $customNotification == '' || $settings == '' || !is_array($settings);
134
    }
135
136
    /**
137
     * Adds a logentry to the custom notification log
138
     *
139
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
140
     * @param string $details Details
141
     * @param int $emailsSent E-Mails sent
142
     *
143
     * @return void
144
     */
145 1
    public function createCustomNotificationLogentry($event, $details, $emailsSent)
146
    {
147 1
        $notificationlogEntry = new \DERHANSEN\SfEventMgt\Domain\Model\CustomNotificationLog();
148 1
        $notificationlogEntry->setEvent($event);
149 1
        $notificationlogEntry->setDetails($details);
150 1
        $notificationlogEntry->setEmailsSent($emailsSent);
151 1
        $notificationlogEntry->setCruserId($GLOBALS['BE_USER']->user['uid']);
152 1
        $this->customNotificationLogRepository->add($notificationlogEntry);
153 1
    }
154
155
    /**
156
     * Sends a message to the user based on the given type
157
     *
158
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
159
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration Registration
160
     * @param array $settings Settings
161
     * @param int $type Type
162
     * @param string $customNotification CustomNotification
163
     *
164
     * @return bool TRUE if successful, else FALSE
165
     */
166 17
    public function sendUserMessage($event, $registration, $settings, $type, $customNotification = '')
167
    {
168 17
        list($template, $subject) = $this->getUserMessageTemplateSubject($settings, $type, $customNotification);
169
170 17
        if (is_null($event) || is_null($registration) || !is_array($settings) || (substr($template, -5) != '.html')) {
171 2
            return false;
172
        }
173
174 15
        if (!$registration->isIgnoreNotifications()) {
175 10
            $body = $this->getNotificationBody($event, $registration, $template, $settings);
176 10
            $attachments = $this->attachmentService->getAttachments(
177 10
                $settings,
178 10
                $registration,
179 10
                $type,
180
                MessageRecipient::USER
181 10
            );
182 10
            return $this->emailService->sendEmailMessage(
183 10
                $settings['notification']['senderEmail'],
184 10
                $registration->getEmail(),
185 10
                $subject,
186 10
                $body,
187 10
                $settings['notification']['senderName'],
188
                $attachments
189 10
            );
190
        }
191 5
        return false;
192
    }
193
194
    /**
195
     * Returns an array with template and subject for the user message
196
     *
197
     * @param array $settings
198
     * @param int $type Type
199
     * @param string $customNotification
200
     * @return array
201
     */
202 17
    protected function getUserMessageTemplateSubject($settings, $type, $customNotification)
203
    {
204 17
        $template = 'Notification/User/RegistrationNew.html';
205 17
        $subject = $settings['notification']['registrationNew']['userSubject'];
206
        switch ($type) {
207 17
            case MessageType::REGISTRATION_WAITLIST_NEW:
208 3
                $template = 'Notification/User/RegistrationWaitlistNew.html';
209 3
                $subject = $settings['notification']['registrationWaitlistNew']['userSubject'];
210 3
                break;
211 14
            case MessageType::REGISTRATION_CONFIRMED:
212 3
                $template = 'Notification/User/RegistrationConfirmed.html';
213 3
                $subject = $settings['notification']['registrationConfirmed']['userSubject'];
214 3
                break;
215 11
            case MessageType::REGISTRATION_WAITLIST_CONFIRMED:
216 3
                $template = 'Notification/User/RegistrationWaitlistConfirmed.html';
217 3
                $subject = $settings['notification']['registrationWaitlistConfirmed']['userSubject'];
218 3
                break;
219 8
            case MessageType::REGISTRATION_CANCELLED:
220
                $template = 'Notification/User/RegistrationCancelled.html';
221
                $subject = $settings['notification']['registrationCancelled']['userSubject'];
222
                break;
223 8
            case MessageType::CUSTOM_NOTIFICATION:
224 1
                $template = 'Notification/User/Custom/' . $settings['notification']['customNotifications'][$customNotification]['template'];
225 1
                $subject = $settings['notification']['customNotifications'][$customNotification]['subject'];
226 1
                break;
227 7
            case MessageType::REGISTRATION_NEW:
228 7
            default:
229 7
        }
230
        return [
231 17
            $template,
232
            $subject
233 17
        ];
234
    }
235
236
    /**
237
     * Sends a message to the admin based on the given type
238
     *
239
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
240
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration Registration
241
     * @param array $settings Settings
242
     * @param int $type Type
243
     *
244
     * @return bool TRUE if successful, else FALSE
245
     */
246 26
    public function sendAdminMessage($event, $registration, $settings, $type)
247
    {
248 26
        list($template, $subject) = $this->getAdminMessageTemplateSubject($settings, $type);
249
250
251 26
        if (is_null($event) || is_null($registration || !is_array($settings)) ||
252 25
            ($event->getNotifyAdmin() === false && $event->getNotifyOrganisator() === false)
253 26
        ) {
254 6
            return false;
255
        }
256
257 20
        $allEmailsSent = true;
258 20
        $body = $this->getNotificationBody($event, $registration, $template, $settings);
259 20
        $attachments = $this->attachmentService->getAttachments(
260 20
            $settings,
261 20
            $registration,
262 20
            $type,
263
            MessageRecipient::ADMIN
264 20
        );
265 20
        if ($event->getNotifyAdmin()) {
266 15
            $adminEmailArr = GeneralUtility::trimExplode(',', $settings['notification']['adminEmail'], true);
267 15
            foreach ($adminEmailArr as $adminEmail) {
268 15
                $allEmailsSent = $allEmailsSent && $this->emailService->sendEmailMessage(
269 15
                    $settings['notification']['senderEmail'],
270 15
                    $adminEmail,
271 15
                    $subject,
272 15
                    $body,
273 15
                    $settings['notification']['senderName'],
274
                    $attachments
275 15
                );
276 15
            }
277 15
        }
278 20
        if ($event->getNotifyOrganisator() && $event->getOrganisator()) {
279 5
            $allEmailsSent = $allEmailsSent && $this->emailService->sendEmailMessage(
280 5
                $settings['notification']['senderEmail'],
281 5
                $event->getOrganisator()->getEmail(),
282 5
                $subject,
283 5
                $body,
284 5
                $settings['notification']['senderName'],
285
                $attachments
286 5
            );
287 5
        }
288 20
        return $allEmailsSent;
289
    }
290
291
    /**
292
     * Returns an array with template and subject for the admin message
293
     *
294
     * @param array $settings
295
     * @param int $type Type
296
     * @return array
297
     */
298 26
    protected function getAdminMessageTemplateSubject($settings, $type)
299
    {
300 26
        $template = 'Notification/Admin/RegistrationNew.html';
301 26
        $subject = $settings['notification']['registrationNew']['adminSubject'];
302
        switch ($type) {
303 26
            case MessageType::REGISTRATION_WAITLIST_NEW:
304 5
                $template = 'Notification/Admin/RegistrationWaitlistNew.html';
305 5
                $subject = $settings['notification']['registrationWaitlistNew']['adminSubject'];
306 5
                break;
307 21
            case MessageType::REGISTRATION_CONFIRMED:
308 5
                $template = 'Notification/Admin/RegistrationConfirmed.html';
309 5
                $subject = $settings['notification']['registrationConfirmed']['adminSubject'];
310 5
                break;
311 16
            case MessageType::REGISTRATION_WAITLIST_CONFIRMED:
312 5
                $template = 'Notification/Admin/RegistrationWaitlistConfirmed.html';
313 5
                $subject = $settings['notification']['registrationWaitlistConfirmed']['adminSubject'];
314 5
                break;
315 11
            case MessageType::REGISTRATION_CANCELLED:
316
                $template = 'Notification/Admin/RegistrationCancelled.html';
317
                $subject = $settings['notification']['registrationCancelled']['adminSubject'];
318
                break;
319 11
            case MessageType::REGISTRATION_NEW:
320 11
            default:
321 11
        }
322
        return [
323 26
            $template,
324
            $subject
325 26
        ];
326
    }
327
328
    /**
329
     * Returns the rendered HTML for the given template
330
     *
331
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
332
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration Registration
333
     * @param string $template Template
334
     * @param array $settings Settings
335
     *
336
     * @return string
337
     */
338 30
    protected function getNotificationBody($event, $registration, $template, $settings)
339
    {
340
        /** @var \TYPO3\CMS\Fluid\View\StandaloneView $emailView */
341 30
        $emailView = $this->objectManager->get('TYPO3\\CMS\\Fluid\\View\\StandaloneView');
342 30
        $emailView->setFormat('html');
343 30
        $layoutRootPaths = $this->fluidStandaloneService->getTemplateFolders('layout');
344 30
        $partialRootPaths = $this->fluidStandaloneService->getTemplateFolders('partial');
345
346 30
        if (TYPO3_MODE === 'BE' && $registration->getLanguage() !== '') {
347
            // Temporary set Language of current BE user to given language
348
            $GLOBALS['BE_USER']->uc['lang'] = $registration->getLanguage();
349
            $emailView->getRequest()->setControllerExtensionName('SfEventMgt');
350
        }
351
352 30
        $emailView->setLayoutRootPaths($layoutRootPaths);
353 30
        $emailView->setPartialRootPaths($partialRootPaths);
354 30
        $emailView->setTemplatePathAndFilename($this->fluidStandaloneService->getTemplatePath($template));
355 30
        $emailView->assignMultiple([
356 30
            'event' => $event,
357 30
            'registration' => $registration,
358 30
            'settings' => $settings,
359 30
            'hmac' => $this->hashService->generateHmac('reg-' . $registration->getUid()),
360 30
            'reghmac' => $this->hashService->appendHmac((string)$registration->getUid())
361 30
        ]);
362 30
        $emailBody = $emailView->render();
363 30
        return $emailBody;
364
    }
365
}
366