FlashMessageQueue.php 9.68 KB
Newer Older
1
<?php
2

3
/*
4
 * This file is part of the TYPO3 CMS project.
5
 *
6
7
8
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
9
 *
10
11
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
12
 *
13
14
 * The TYPO3 project - inspiring people to share!
 */
Wouter Wolters's avatar
Wouter Wolters committed
15

16
17
namespace TYPO3\CMS\Core\Messaging;

18
use TYPO3\CMS\Core\Authentication\AbstractUserAuthentication;
19
use TYPO3\CMS\Core\Exception;
20
21
use TYPO3\CMS\Core\Messaging\Renderer\FlashMessageRendererInterface;
use TYPO3\CMS\Core\Utility\GeneralUtility;
Benni Mack's avatar
Benni Mack committed
22
23
use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
24

25
26
27
/**
 * A class which collects and renders flash messages.
 */
28
class FlashMessageQueue extends \SplQueue implements \JsonSerializable
29
{
30
31
32
    public const FLASHMESSAGE_QUEUE = 'core.template.flashMessages';
    public const NOTIFICATION_QUEUE = 'core.template.notifications';

33
34
35
36
37
38
    /**
     * A unique identifier for this queue
     *
     * @var string
     */
    protected $identifier;
39

40
41
42
43
44
45
46
47
    /**
     * @param string $identifier The unique identifier for this queue
     */
    public function __construct($identifier)
    {
        $this->identifier = $identifier;
    }

48
49
50
51
52
53
54
55
    /**
     * @return string
     */
    public function getIdentifier()
    {
        return $this->identifier;
    }

56
57
58
59
60
61
    /**
     * Adds a message either to the BE_USER session (if the $message has the storeInSession flag set)
     * or it enqueues the message.
     *
     * @param FlashMessage $message Instance of \TYPO3\CMS\Core\Messaging\FlashMessage, representing a message
     * @throws \TYPO3\CMS\Core\Exception
62
     * @return FlashMessageQueue Self to allow chaining
63
     * @todo: Set return type to void in v12 as breaking patch and drop #[\ReturnTypeWillChange]
64
     */
65
    #[\ReturnTypeWillChange]
66
    public function enqueue($message): FlashMessageQueue
67
68
    {
        if (!($message instanceof FlashMessage)) {
69
            throw new Exception(
70
                'FlashMessageQueue::enqueue() expects an object of type \TYPO3\CMS\Core\Messaging\FlashMessage but got type "' . get_debug_type($message) . '"',
71
72
73
74
75
76
77
78
                1376833554
            );
        }
        if ($message->isSessionMessage()) {
            $this->addFlashMessageToSession($message);
        } else {
            parent::enqueue($message);
        }
79
        return $this;
80
81
82
83
84
85
86
87
88
89
90
    }

    /**
     * @param FlashMessage $message
     */
    public function addMessage(FlashMessage $message)
    {
        $this->enqueue($message);
    }

    /**
91
     * This method is empty, as it will not move any flash message (e.g. from the session)
92
93
     *
     * @todo: Set return type to mixed when PHP >= 8.0 is required and drop #[\ReturnTypeWillChange]
94
     */
95
    #[\ReturnTypeWillChange]
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
    public function dequeue()
    {
        // deliberately empty
    }

    /**
     * Adds the given flash message to the array of
     * flash messages that will be stored in the session.
     *
     * @param FlashMessage $message
     */
    protected function addFlashMessageToSession(FlashMessage $message)
    {
        $queuedFlashMessages = $this->getFlashMessagesFromSession();
        $queuedFlashMessages[] = $message;
        $this->storeFlashMessagesInSession($queuedFlashMessages);
    }

    /**
     * Returns all messages from the current PHP session and from the current request.
     *
     * @param int $severity Optional severity, must be one of \TYPO3\CMS\Core\Messaging\AbstractMessage constants
     * @return FlashMessage[]
     */
    public function getAllMessages($severity = null)
    {
        // Get messages from user session
        $queuedFlashMessagesFromSession = $this->getFlashMessagesFromSession();
        $queuedFlashMessages = array_merge($queuedFlashMessagesFromSession, $this->toArray());
        if ($severity !== null) {
126
            $filteredFlashMessages = [];
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
            foreach ($queuedFlashMessages as $message) {
                if ($message->getSeverity() === $severity) {
                    $filteredFlashMessages[] = $message;
                }
            }
            return $filteredFlashMessages;
        }

        return $queuedFlashMessages;
    }

    /**
     * Returns all messages from the current PHP session and from the current request.
     * After fetching the messages the internal queue and the message queue in the session
     * will be emptied.
     *
     * @param int $severity Optional severity, must be one of \TYPO3\CMS\Core\Messaging\AbstractMessage constants
     * @return FlashMessage[]
     */
    public function getAllMessagesAndFlush($severity = null)
    {
        $queuedFlashMessages = $this->getAllMessages($severity);
        // Reset messages in user session
        $this->removeAllFlashMessagesFromSession($severity);
        // Reset internal messages
        $this->clear($severity);
        return $queuedFlashMessages;
    }

    /**
     * Stores given flash messages in the session
     *
     * @param FlashMessage[] $flashMessages
     */
    protected function storeFlashMessagesInSession(array $flashMessages = null)
    {
163
164
165
        if (is_array($flashMessages)) {
            $flashMessages = array_map('json_encode', $flashMessages);
        }
166
167
168
169
        $user = $this->getUserByContext();
        if ($user instanceof AbstractUserAuthentication) {
            $user->setAndSaveSessionData($this->identifier, $flashMessages);
        }
170
171
172
173
174
175
176
177
178
    }

    /**
     * Removes all flash messages from the session
     *
     * @param int $severity Optional severity, must be one of \TYPO3\CMS\Core\Messaging\AbstractMessage constants
     */
    protected function removeAllFlashMessagesFromSession($severity = null)
    {
179
180
181
        if (!$this->getUserByContext() instanceof AbstractUserAuthentication) {
            return;
        }
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
        if ($severity === null) {
            $this->storeFlashMessagesInSession(null);
        } else {
            $messages = $this->getFlashMessagesFromSession();
            foreach ($messages as $index => $message) {
                if ($message->getSeverity() === $severity) {
                    unset($messages[$index]);
                }
            }
            $this->storeFlashMessagesInSession($messages);
        }
    }

    /**
     * Returns current flash messages from the session, making sure to always
     * return an array.
     *
     * @return FlashMessage[]
     */
201
    protected function getFlashMessagesFromSession(): array
202
    {
203
204
205
        $sessionMessages = [];
        $user = $this->getUserByContext();
        if ($user instanceof AbstractUserAuthentication) {
206
207
208
209
210
            $messagesFromSession = $user->getSessionData($this->identifier);
            $messagesFromSession = is_array($messagesFromSession) ? $messagesFromSession : [];
            foreach ($messagesFromSession as $messageData) {
                $sessionMessages[] = FlashMessage::createFromArray(json_decode($messageData, true));
            }
211
212
        }
        return $sessionMessages;
213
214
215
    }

    /**
216
217
     * Gets user object by context.
     * This class is also used in install tool, where $GLOBALS['BE_USER'] is not set and can be null.
218
     *
219
     * @return AbstractUserAuthentication|null
220
     */
221
    protected function getUserByContext(): ?AbstractUserAuthentication
222
    {
Benni Mack's avatar
Benni Mack committed
223
224
225
        if (($GLOBALS['TSFE'] ?? null) instanceof TypoScriptFrontendController && $GLOBALS['TSFE']->fe_user instanceof FrontendUserAuthentication) {
            return $GLOBALS['TSFE']->fe_user;
        }
226
        return $GLOBALS['BE_USER'] ?? null;
227
228
229
230
231
    }

    /**
     * Fetches and renders all available flash messages from the queue.
     *
232
233
     * @param FlashMessageRendererInterface|null $flashMessageRenderer
     * @return string All flash messages in the queue rendered by context based FlashMessageRendererResolver.
234
     */
235
    public function renderFlashMessages(FlashMessageRendererInterface $flashMessageRenderer = null)
236
237
238
    {
        $content = '';
        $flashMessages = $this->getAllMessagesAndFlush();
239

240
        if (!empty($flashMessages)) {
241
242
            if ($flashMessageRenderer === null) {
                $flashMessageRenderer = GeneralUtility::makeInstance(FlashMessageRendererResolver::class)->resolve();
243
            }
244
            $content = $flashMessageRenderer->render($flashMessages);
245
        }
246

247
248
249
250
251
252
253
254
255
256
        return $content;
    }

    /**
     * Returns all items of the queue as array
     *
     * @return FlashMessage[]
     */
    public function toArray()
    {
257
        $array = [];
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
        $this->rewind();
        while ($this->valid()) {
            $array[] = $this->current();
            $this->next();
        }
        return $array;
    }

    /**
     * Removes all items from the queue
     *
     * @param int $severity Optional severity, must be one of \TYPO3\CMS\Core\Messaging\AbstractMessage constants
     */
    public function clear($severity = null)
    {
        $this->rewind();
        if ($severity === null) {
            while (!$this->isEmpty()) {
                parent::dequeue();
            }
        } else {
279
            $keysToRemove = [];
280
281
282
283
284
285
286
287
288
289
290
291
292
293
            while ($cur = $this->current()) {
                if ($cur->getSeverity() === $severity) {
                    $keysToRemove[] = $this->key();
                }
                $this->next();
            }
            // keys are renumbered when unsetting elements
            // so unset them from last to first
            $keysToRemove = array_reverse($keysToRemove);
            foreach ($keysToRemove as $key) {
                $this->offsetUnset($key);
            }
        }
    }
294
295
296
297
298
299
300
301

    /**
     * @return array Data which can be serialized by json_encode()
     */
    public function jsonSerialize(): array
    {
        return $this->toArray();
    }
302
}