Completed
Push — master ( 07b37d...b10e41 )
by Torben
02:00
created

NotificationService::getTemplatePath()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 9.4285
cc 2
eloc 3
nc 2
nop 2
crap 2
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 \TYPO3\CMS\Core\Utility\GeneralUtility;
19
use \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;
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
     * The configuration manager
39
     *
40
     * @var \TYPO3\CMS\Extbase\Configuration\ConfigurationManager
41
     * @inject
42
     */
43
    protected $configurationManager;
44
45
    /**
46
     * Registration repository
47
     *
48
     * @var \DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository
49
     * @inject
50
     */
51
    protected $registrationRepository = null;
52
53
    /**
54
     * Email Service
55
     *
56
     * @var \DERHANSEN\SfEventMgt\Service\EmailService
57
     * @inject
58
     */
59
    protected $emailService;
60
61
    /**
62
     * Hash Service
63
     *
64
     * @var \TYPO3\CMS\Extbase\Security\Cryptography\HashService
65
     * @inject
66
     */
67
    protected $hashService;
68
69
    /**
70
     * CustomNotificationLogRepository
71
     *
72
     * @var \DERHANSEN\SfEventMgt\Domain\Repository\CustomNotificationLogRepository
73
     * @inject
74
     */
75
    protected $customNotificationLogRepository = null;
76
77
    /**
78
     * Sends a custom notification defined by the given customNotification key
79
     * to all confirmed users of the event
80
     *
81
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
82
     * @param string $customNotification CustomNotification
83
     * @param array $settings Settings
84
     *
85
     * @return int Number of notifications sent
86
     */
87 4
    public function sendCustomNotification($event, $customNotification, $settings)
88
    {
89 4
        if ($this->cantSendCustomNotification($event, $settings, $customNotification)) {
90 1
            return 0;
91
        }
92 3
        $count = 0;
93
94 3
        $constraints = $settings['notification']['customNotifications'][$customNotification]['constraints'];
95 3
        $registrations = $this->registrationRepository->findNotificationRegistrations($event, $constraints);
96 3
        foreach ($registrations as $registration) {
97
            /** @var \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration */
98 3
            if ($registration->isConfirmed() && !$registration->isIgnoreNotifications()) {
99 1
                $result = $this->sendUserMessage(
100 1
                    $event,
101 1
                    $registration,
102 1
                    $settings,
103 1
                    MessageType::CUSTOM_NOTIFICATION,
104
                    $customNotification
105 1
                );
106 1
                if ($result) {
107 1
                    $count += 1;
108 1
                }
109 1
            }
110 3
        }
111 3
        return $count;
112
    }
113
114
    /**
115
     * Returns true if conditions are not met to send a custom notification
116
     *
117
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event
118
     * @param array $settings
119
     * @param string $customNotification
120
     *
121
     * @return bool
122
     */
123 4
    protected function cantSendCustomNotification($event, $settings, $customNotification)
124
    {
125 4
        return is_null($event) || $customNotification == '' || $settings == '' || !is_array($settings);
126
    }
127
128
    /**
129
     * Adds a logentry to the custom notification log
130
     *
131
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
132
     * @param string $details Details
133
     * @param int $emailsSent E-Mails sent
134
     *
135
     * @return void
136
     */
137 1
    public function createCustomNotificationLogentry($event, $details, $emailsSent)
138
    {
139 1
        $notificationlogEntry = new \DERHANSEN\SfEventMgt\Domain\Model\CustomNotificationLog();
140 1
        $notificationlogEntry->setEvent($event);
141 1
        $notificationlogEntry->setDetails($details);
142 1
        $notificationlogEntry->setEmailsSent($emailsSent);
143 1
        $notificationlogEntry->setCruserId($GLOBALS['BE_USER']->user['uid']);
144 1
        $this->customNotificationLogRepository->add($notificationlogEntry);
145 1
    }
146
147
    /**
148
     * Sends a message to the user based on the given type
149
     *
150
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
151
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration Registration
152
     * @param array $settings Settings
153
     * @param int $type Type
154
     * @param string $customNotification CustomNotification
155
     *
156
     * @return bool TRUE if successful, else FALSE
157
     */
158 11
    public function sendUserMessage($event, $registration, $settings, $type, $customNotification = '')
159
    {
160 11
        list($template, $subject) = $this->getUserMessageTemplateSubject($settings, $type, $customNotification);
161
162 11
        if (is_null($event) || is_null($registration) || !is_array($settings) || (substr($template, -5) != '.html')) {
163 2
            return false;
164
        }
165
166 9
        if (!$registration->isIgnoreNotifications()) {
167 6
            $body = $this->getNotificationBody($event, $registration, $template, $settings);
168 6
            return $this->emailService->sendEmailMessage(
169 6
                $settings['notification']['senderEmail'],
170 6
                $registration->getEmail(),
171 6
                $subject,
172 6
                $body,
173 6
                $settings['notification']['senderName']
174 6
            );
175
        }
176 3
        return false;
177
    }
178
179
    /**
180
     * Returns an array with template and subject for the user message
181
     *
182
     * @param array $settings
183
     * @param int $type Type
184
     * @param string $customNotification
185
     * @return array
186
     */
187 11
    protected function getUserMessageTemplateSubject($settings, $type, $customNotification)
188
    {
189 11
        $template = 'Notification/User/RegistrationNew.html';
190 11
        $subject = $settings['notification']['registrationNew']['userSubject'];
191
        switch ($type) {
192 11
            case MessageType::REGISTRATION_CONFIRMED:
193 3
                $template = 'Notification/User/RegistrationConfirmed.html';
194 3
                $subject = $settings['notification']['registrationConfirmed']['userSubject'];
195 3
                break;
196 8
            case MessageType::REGISTRATION_CANCELLED:
197
                $template = 'Notification/User/RegistrationCancelled.html';
198
                $subject = $settings['notification']['registrationCancelled']['userSubject'];
199
                break;
200 8
            case MessageType::CUSTOM_NOTIFICATION:
201 1
                $template = 'Notification/User/Custom/' . $settings['notification']['customNotifications'][$customNotification]['template'];
202 1
                $subject = $settings['notification']['customNotifications'][$customNotification]['subject'];
203 1
                break;
204 7
            case MessageType::REGISTRATION_NEW:
205 7
            default:
206 7
        }
207
        return [
208 11
            $template,
209
            $subject
210 11
        ];
211
    }
212
213
    /**
214
     * Sends a message to the admin based on the given type
215
     *
216
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
217
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration Registration
218
     * @param array $settings Settings
219
     * @param int $type Type
220
     *
221
     * @return bool TRUE if successful, else FALSE
222
     */
223 16
    public function sendAdminMessage($event, $registration, $settings, $type)
224
    {
225 16
        list($template, $subject) = $this->getAdminMessageTemplateSubject($settings, $type);
226
227
228 16
        if (is_null($event) || is_null($registration || !is_array($settings)) ||
229 15
            ($event->getNotifyAdmin() === false && $event->getNotifyOrganisator() === false)
230 16
        ) {
231 4
            return false;
232
        }
233
234 12
        $allEmailsSent = true;
235 12
        $body = $this->getNotificationBody($event, $registration, $template, $settings);
236 12
        if ($event->getNotifyAdmin()) {
237 9
            $adminEmailArr = GeneralUtility::trimExplode(',', $settings['notification']['adminEmail'], true);
238 9
            foreach ($adminEmailArr as $adminEmail) {
239 9
                $allEmailsSent = $allEmailsSent && $this->emailService->sendEmailMessage(
240 9
                    $settings['notification']['senderEmail'],
241 9
                    $adminEmail,
242 9
                    $subject,
243 9
                    $body,
244 9
                    $settings['notification']['senderName']
245 9
                );
246 9
            }
247 9
        }
248 12
        if ($event->getNotifyOrganisator() && $event->getOrganisator()) {
249 3
            $allEmailsSent = $allEmailsSent && $this->emailService->sendEmailMessage(
250 3
                $settings['notification']['senderEmail'],
251 3
                $event->getOrganisator()->getEmail(),
252 3
                $subject,
253 3
                $body,
254 3
                $settings['notification']['senderName']
255 3
            );
256 3
        }
257 12
        return $allEmailsSent;
258
    }
259
260
    /**
261
     * Returns an array with template and subject for the admin message
262
     *
263
     * @param array $settings
264
     * @param int $type Type
265
     * @return array
266
     */
267 16
    protected function getAdminMessageTemplateSubject($settings, $type)
268
    {
269 16
        $template = 'Notification/Admin/RegistrationNew.html';
270 16
        $subject = $settings['notification']['registrationNew']['adminSubject'];
271
        switch ($type) {
272 16
            case MessageType::REGISTRATION_CONFIRMED:
273 5
                $template = 'Notification/Admin/RegistrationConfirmed.html';
274 5
                $subject = $settings['notification']['registrationConfirmed']['adminSubject'];
275 5
                break;
276 11
            case MessageType::REGISTRATION_CANCELLED:
277
                $template = 'Notification/Admin/RegistrationCancelled.html';
278
                $subject = $settings['notification']['registrationCancelled']['adminSubject'];
279
                break;
280 11
            case MessageType::REGISTRATION_NEW:
281 11
            default:
282 11
        }
283
        return [
284 16
            $template,
285
            $subject
286 16
        ];
287
    }
288
289
    /**
290
     * Returns the rendered HTML for the given template
291
     *
292
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
293
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration Registration
294
     * @param string $template Template
295
     * @param array $settings Settings
296
     *
297
     * @return string
298
     */
299 18
    protected function getNotificationBody($event, $registration, $template, $settings)
300
    {
301
        /** @var \TYPO3\CMS\Fluid\View\StandaloneView $emailView */
302 18
        $emailView = $this->objectManager->get('TYPO3\\CMS\\Fluid\\View\\StandaloneView');
303 18
        $emailView->setFormat('html');
304 18
        $layoutRootPaths = $this->getTemplateFolders('layout');
305 18
        $partialRootPaths = $this->getTemplateFolders('partial');
306
307 18
        if (TYPO3_MODE === 'BE' && $registration->getLanguage() !== '') {
308
            // Temporary set Language of current BE user to given language
309
            $GLOBALS['BE_USER']->uc['lang'] = $registration->getLanguage();
310
            $emailView->getRequest()->setControllerExtensionName('SfEventMgt');
311
        }
312
313 18
        $emailView->setLayoutRootPaths($layoutRootPaths);
314 18
        $emailView->setPartialRootPaths($partialRootPaths);
315 18
        $emailView->setTemplatePathAndFilename($this->getTemplatePath($template));
316 18
        $emailView->assignMultiple([
317 18
            'event' => $event,
318 18
            'registration' => $registration,
319 18
            'settings' => $settings,
320 18
            'hmac' => $this->hashService->generateHmac('reg-' . $registration->getUid()),
321 18
            'reghmac' => $this->hashService->appendHmac((string)$registration->getUid())
322 18
        ]);
323 18
        $emailBody = $emailView->render();
324 18
        return $emailBody;
325
    }
326
327
    /**
328
     * Returns the template folders for the given part
329
     *
330
     * @param string $part
331
     * @return array
332
     * @throws \TYPO3\CMS\Extbase\Configuration\Exception\InvalidConfigurationTypeException
333
     */
334 18
    protected function getTemplateFolders($part = 'template')
335
    {
336 18
        $extbaseConfig = $this->configurationManager->getConfiguration(
337
            ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK
338 18
        );
339
340 18
        if (!empty($extbaseConfig[$part . 'RootPaths'])) {
341
            $templatePaths = $extbaseConfig[$part . 'RootPaths'];
342
        }
343 18
        if (empty($templatePaths)) {
344 18
            $path = $extbaseConfig[$part . 'RootPath'];
345 18
            if (!empty($path)) {
346
                $templatePaths = $path;
347
            }
348 18
        }
349 18
        if (empty($templatePaths)) {
350 18
            $templatePaths = [];
351 18
            $templatePaths[] = 'EXT:sf_event_mgt/Resources/Private/' . ucfirst($part) . 's/';
352 18
        }
353
354 18
        $absolutePaths = [];
355 18
        foreach ($templatePaths as $templatePath) {
356 18
            $absolutePaths[] = GeneralUtility::getFileAbsFileName($templatePath);
357 18
        }
358 18
        return $absolutePaths;
359
    }
360
361
    /**
362
     * Return path and filename for a file or path.
363
     *        Only the first existing file/path will be returned.
364
     *        respect *RootPaths and *RootPath
365
     *
366
     * @param string $pathAndFilename e.g. Email/Name.html
367
     * @param string $part "template", "partial", "layout"
368
     * @return string Filename/path
369
     */
370 18
    protected function getTemplatePath($pathAndFilename, $part = 'template')
371
    {
372 18
        $matches = $this->getTemplatePaths($pathAndFilename, $part);
373 18
        return !empty($matches) ? end($matches) : '';
374
    }
375
376
    /**
377
     * Return path and filename for one or many files/paths.
378
     *        Only existing files/paths will be returned.
379
     *        respect *RootPaths and *RootPath
380
     *
381
     * @param string $pathAndFilename Path/filename (Email/Name.html) or path
382
     * @param string $part "template", "partial", "layout"
383
     * @return array All existing matches found
384
     */
385 18
    protected function getTemplatePaths($pathAndFilename, $part = 'template')
386
    {
387 18
        $matches = [];
388 18
        $absolutePaths = $this->getTemplateFolders($part);
389 18
        foreach ($absolutePaths as $absolutePath) {
390 18
            if (file_exists($absolutePath . $pathAndFilename)) {
391 18
                $matches[] = $absolutePath . $pathAndFilename;
392 18
            }
393 18
        }
394 18
        return $matches;
395
    }
396
}