2 namespace wcf\system\user\notification
;
3 use wcf\data\
object\type\ObjectType
;
4 use wcf\data\
object\type\ObjectTypeCache
;
5 use wcf\data\user\notification\event\recipient\UserNotificationEventRecipientList
;
6 use wcf\data\user\notification\event\UserNotificationEventList
;
7 use wcf\data\user\notification\UserNotification
;
8 use wcf\data\user\notification\UserNotificationAction
;
9 use wcf\data\user\User
;
10 use wcf\data\user\UserEditor
;
11 use wcf\data\user\UserProfile
;
12 use wcf\form\NotificationUnsubscribeForm
;
13 use wcf\system\background\job\NotificationEmailDeliveryBackgroundJob
;
14 use wcf\system\background\BackgroundQueueHandler
;
15 use wcf\system\cache\builder\UserNotificationEventCacheBuilder
;
16 use wcf\system\cache\runtime\UserProfileRuntimeCache
;
17 use wcf\system\database\util\PreparedStatementConditionBuilder
;
18 use wcf\system\email\mime\MimePartFacade
;
19 use wcf\system\email\mime\RecipientAwareTextMimePart
;
20 use wcf\system\email\Email
;
21 use wcf\system\email\UserMailbox
;
22 use wcf\system\event\EventHandler
;
23 use wcf\system\exception\SystemException
;
24 use wcf\system\request\LinkHandler
;
25 use wcf\system\user\notification\event\IUserNotificationEvent
;
26 use wcf\system\user\notification\
object\type\IUserNotificationObjectType
;
27 use wcf\system\user\notification\
object\IUserNotificationObject
;
28 use wcf\system\user\storage\UserStorageHandler
;
29 use wcf\system\SingletonFactory
;
33 * Handles user notifications.
35 * @author Marcel Werk, Oliver Kliebisch
36 * @copyright 2001-2019 WoltLab GmbH, Oliver Kliebisch
37 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
38 * @package WoltLabSuite\Core\System\User\Notification
40 class UserNotificationHandler
extends SingletonFactory
{
42 * list of available object types
43 * @var IUserNotificationObjectType[]
45 protected $availableObjectTypes = [];
48 * list of available events
49 * @var IUserNotificationEvent[][]
51 protected $availableEvents = [];
54 * number of outstanding notifications
57 protected $notificationCount = null;
60 * list of object types
63 protected $objectTypes = [];
68 protected function init() {
69 // get available object types
70 $this->objectTypes
= ObjectTypeCache
::getInstance()->getObjectTypes('com.woltlab.wcf.notification.objectType');
71 foreach ($this->objectTypes
as $typeName => $object) {
72 $this->availableObjectTypes
[$typeName] = $object->getProcessor();
75 // get available events
76 $this->availableEvents
= UserNotificationEventCacheBuilder
::getInstance()->getData();
80 * Triggers a notification event.
82 * @param string $eventName
83 * @param string $objectType
84 * @param IUserNotificationObject $notificationObject
85 * @param integer[] $recipientIDs
86 * @param mixed[] $additionalData
87 * @param integer $baseObjectID
88 * @throws SystemException
90 public function fireEvent($eventName, $objectType, IUserNotificationObject
$notificationObject, array $recipientIDs, array $additionalData = [], $baseObjectID = 0) {
91 // check given object type and event name
92 if (!isset($this->availableEvents
[$objectType][$eventName])) {
93 throw new SystemException("Unknown event ".$objectType."-".$eventName." given");
97 $objectTypeObject = $this->availableObjectTypes
[$objectType];
98 $event = $this->availableEvents
[$objectType][$eventName];
100 // get author's profile
102 if ($notificationObject->getAuthorID()) {
103 if ($notificationObject->getAuthorID() == WCF
::getUser()->userID
) {
104 $userProfile = new UserProfile(WCF
::getUser());
107 $userProfile = UserProfileRuntimeCache
::getInstance()->getObject($notificationObject->getAuthorID());
110 if ($userProfile === null) {
111 $userProfile = new UserProfile(new User(null, []));
115 $event->setObject(new UserNotification(null, []), $notificationObject, $userProfile, $additionalData);
116 $event->setAuthors([$event->getAuthorID() => $event->getAuthor()]);
119 'eventName' => $eventName,
120 'objectType' => $objectType,
121 'notificationObject' => $notificationObject,
122 'recipientIDs' => $recipientIDs,
123 'additionalData' => $additionalData,
124 'baseObjectID' => $baseObjectID,
125 'objectTypeObject' => $objectTypeObject,
126 'userProfile' => $userProfile,
129 // @deprecated 5.2 This event exposes incomplete data and should not be used, please use the following events instead.
130 EventHandler
::getInstance()->fireAction($this, 'fireEvent', $parameters);
132 // find existing notifications
133 $conditions = new PreparedStatementConditionBuilder();
134 $conditions->add("userID IN (?)", [$recipientIDs]);
135 $conditions->add("eventID = ?", [$event->eventID
]);
136 $conditions->add("eventHash = ?", [$event->getEventHash()]);
137 $conditions->add("confirmTime = ?", [0]);
139 $sql = "SELECT notificationID, userID
140 FROM wcf".WCF_N
."_user_notification
142 $statement = WCF
::getDB()->prepareStatement($sql);
143 $statement->execute($conditions->getParameters());
144 $notifications = $statement->fetchMap('userID', 'notificationID');
146 // check if event supports stacking and author should be added
147 if (!empty($notifications) && $event->isStackable()) {
148 $conditions = new PreparedStatementConditionBuilder();
149 $conditions->add("notificationID IN (?)", [array_values($notifications)]);
150 if ($notificationObject->getAuthorID()) {
151 $conditions->add("authorID = ?", [$notificationObject->getAuthorID()]);
154 $conditions->add("authorID IS NULL");
157 $sql = "SELECT notificationID
158 FROM wcf".WCF_N
."_user_notification_author
160 $statement = WCF
::getDB()->prepareStatement($sql);
161 $statement->execute($conditions->getParameters());
162 $notificationIDs = $statement->fetchAll(\PDO
::FETCH_COLUMN
);
164 // filter array of existing notifications and remove values which
165 // do not have a notification from this author yet (inverse logic!)
166 foreach ($notifications as $userID => $notificationID) {
167 if (!in_array($notificationID, $notificationIDs)) {
168 unset($notifications[$userID]);
172 if (!empty($notificationIDs)) {
173 // update trigger count
174 $sql = "UPDATE wcf".WCF_N
."_user_notification
175 SET timesTriggered = timesTriggered + ?,
176 guestTimesTriggered = guestTimesTriggered + ?
177 WHERE notificationID = ?";
178 $statement = WCF
::getDB()->prepareStatement($sql);
180 WCF
::getDB()->beginTransaction();
181 foreach ($notificationIDs as $notificationID) {
182 $statement->execute([
184 $notificationObject->getAuthorID() ?
0 : 1,
188 WCF
::getDB()->commitTransaction();
190 $triggerCountParameters = $parameters;
191 $triggerCountParameters['updateTriggerCount'] = $notificationIDs;
192 EventHandler
::getInstance()->fireAction($this, 'updateTriggerCount', $triggerCountParameters);
193 unset($triggerCountParameters);
197 $recipientIDs = array_diff($recipientIDs, array_keys($notifications));
198 if (empty($recipientIDs)) {
202 // remove recipients that are blocking the current user
203 if ($userProfile->getUserID()) {
204 // we use a live query here to avoid offloading this to the UserProfile
205 // class, as we're potentially dealing with a lot of users and loading
206 // their user storage data can get really expensive
207 $conditions = new PreparedStatementConditionBuilder();
208 $conditions->add("userID IN (?)", [$recipientIDs]);
209 $conditions->add("ignoreUserID = ?", [$userProfile->getUserID()]);
211 $sql = "SELECT userID
212 FROM wcf" . WCF_N
. "_user_ignore
214 $statement = WCF
::getDB()->prepareStatement($sql);
215 $statement->execute($conditions->getParameters());
217 while ($userID = $statement->fetchColumn()) {
218 $userIDs[] = $userID;
221 if (!empty($userIDs)) {
222 $recipientIDs = array_diff($recipientIDs, $userIDs);
225 if (empty($recipientIDs)) {
231 $recipientList = new UserNotificationEventRecipientList();
232 $recipientList->getConditionBuilder()->add('event_to_user.eventID = ?', [$event->eventID
]);
233 $recipientList->getConditionBuilder()->add('event_to_user.userID IN (?)', [$recipientIDs]);
234 $recipientList->readObjects();
235 $recipients = $recipientList->getObjects();
236 if (!empty($recipients)) {
238 'authorID' => $event->getAuthorID() ?
: null,
240 'eventID' => $event->eventID
,
241 'authorID' => $event->getAuthorID() ?
: null,
242 'objectID' => $notificationObject->getObjectID(),
243 'baseObjectID' => $baseObjectID,
244 'eventHash' => $event->getEventHash(),
245 'packageID' => $objectTypeObject->packageID
,
246 'mailNotified' => $event->supportsEmailNotification() ?
0 : 1,
248 'additionalData' => serialize($additionalData)
250 'recipients' => $recipients
253 if ($event->isStackable()) {
254 $data['notifications'] = $notifications;
256 $action = new UserNotificationAction([], 'createStackable', $data);
259 $data['data']['timesTriggered'] = 1;
260 $action = new UserNotificationAction([], 'createDefault', $data);
263 $result = $action->executeAction();
264 $notifications = $result['returnValues'];
266 // send notifications
267 if ($event->supportsEmailNotification()) {
268 foreach ($recipients as $recipient) {
269 if ($recipient->mailNotificationType
== 'instant') {
270 if (isset($notifications[$recipient->userID
]) && $notifications[$recipient->userID
]['isNew']) {
271 $event->setObject($notifications[$recipient->userID
]['object'], $notificationObject, $userProfile, $additionalData);
272 $event->setAuthors([$userProfile->userID
=> $userProfile]);
273 $this->sendInstantMailNotification($notifications[$recipient->userID
]['object'], $recipient, $event);
279 // reset notification count
280 UserStorageHandler
::getInstance()->reset(array_keys($recipients), 'userNotificationCount');
282 $parameters['notifications'] = $notifications;
283 $parameters['recipients'] = $recipients;
284 EventHandler
::getInstance()->fireAction($this, 'createdNotification', $parameters);
289 * Returns the number of outstanding notifications for the active user.
291 * @param boolean $skipCache
294 public function getNotificationCount($skipCache = false) {
295 if ($this->notificationCount
=== null ||
$skipCache) {
296 $this->notificationCount
= 0;
298 if (WCF
::getUser()->userID
) {
299 $data = UserStorageHandler
::getInstance()->getField('userNotificationCount');
301 // cache does not exist or is outdated
302 if ($data === null ||
$skipCache) {
303 $sql = "SELECT COUNT(*)
304 FROM wcf".WCF_N
."_user_notification
306 AND confirmTime = ?";
307 $statement = WCF
::getDB()->prepareStatement($sql);
308 $statement->execute([
309 WCF
::getUser()->userID
,
313 $this->notificationCount
= $statement->fetchSingleColumn();
315 // update storage data
316 UserStorageHandler
::getInstance()->update(WCF
::getUser()->userID
, 'userNotificationCount', serialize($this->notificationCount
));
319 $this->notificationCount
= unserialize($data);
324 return $this->notificationCount
;
328 * Counts all existing notifications for current user and returns it.
332 public function countAllNotifications() {
333 $sql = "SELECT COUNT(*)
334 FROM wcf".WCF_N
."_user_notification
336 $statement = WCF
::getDB()->prepareStatement($sql);
337 $statement->execute([WCF
::getUser()->userID
]);
339 return $statement->fetchSingleColumn();
343 * Returns a list of notifications.
345 * @param integer $limit
346 * @param integer $offset
347 * @param boolean $showConfirmedNotifications DEPRECATED
350 public function getNotifications($limit = 5, $offset = 0, $showConfirmedNotifications = false) {
351 $notifications = $this->fetchNotifications($limit, $offset);
353 return $this->processNotifications($notifications);
357 * Returns a mixed list of notifications, containing leading unconfirmed notifications in their chronological
358 * order regardless of the overall order of already confirmed items.
362 public function getMixedNotifications() {
363 $notificationCount = $this->getNotificationCount(true);
366 if ($notificationCount > 0) {
367 $notifications = $this->fetchNotifications(10, 0, 0);
370 $count = count($notifications);
371 $limit = 10 - $count;
374 $notifications = array_merge($notifications, $this->fetchNotifications($limit, 0, 1));
377 $returnValues = $this->processNotifications($notifications);
378 $returnValues['notificationCount'] = $notificationCount;
380 return $returnValues;
384 * Fetches a list of notifications based upon given conditions.
386 * @param integer $limit
387 * @param integer $offset
388 * @param mixed $filterByConfirmed
389 * @return UserNotification[]
391 protected function fetchNotifications($limit, $offset, $filterByConfirmed = null) {
392 // build enormous query
393 $conditions = new PreparedStatementConditionBuilder();
394 $conditions->add("notification.userID = ?", [WCF
::getUser()->userID
]);
396 if ($filterByConfirmed !== null) {
397 // consider only unconfirmed notifications
398 if ($filterByConfirmed == 0) {
399 $conditions->add("notification.confirmTime = ?", [0]);
402 // consider only notifications marked as confirmed in the past 48 hours (86400 = 1 day)
403 $conditions->add("notification.confirmTime >= ?", [TIME_NOW
- (2 * 86400)]);
407 $sql = "SELECT notification.*, notification_event.eventID, object_type.objectType
408 FROM wcf".WCF_N
."_user_notification notification
409 LEFT JOIN wcf".WCF_N
."_user_notification_event notification_event
410 ON (notification_event.eventID = notification.eventID)
411 LEFT JOIN wcf".WCF_N
."_object_type object_type
412 ON (object_type.objectTypeID = notification_event.objectTypeID)
414 ORDER BY notification.time DESC";
415 $statement = WCF
::getDB()->prepareStatement($sql, $limit, $offset);
416 $statement->execute($conditions->getParameters());
418 return $statement->fetchObjects(UserNotification
::class, 'notificationID');
422 * Processes a list of notification objects.
424 * @param UserNotification[] $notificationObjects
427 public function processNotifications(array $notificationObjects) {
428 // return an empty set if no notifications exist
429 if (empty($notificationObjects)) {
432 'notifications' => []
436 $eventIDs = $notificationIDs = $objectTypes = [];
437 foreach ($notificationObjects as $notification) {
438 // cache object types
439 if (!isset($objectTypes[$notification->objectType
])) {
440 $objectTypes[$notification->objectType
] = [
441 'objectType' => $this->availableObjectTypes
[$notification->objectType
],
447 $objectTypes[$notification->objectType
]['objectIDs'][] = $notification->objectID
;
448 $eventIDs[] = $notification->eventID
;
449 $notificationIDs[] = $notification->notificationID
;
453 $conditions = new PreparedStatementConditionBuilder();
454 $conditions->add("notificationID IN (?)", [$notificationIDs]);
455 $sql = "SELECT notificationID, authorID
456 FROM wcf".WCF_N
."_user_notification_author
459 $statement = WCF
::getDB()->prepareStatement($sql);
460 $statement->execute($conditions->getParameters());
461 $authorIDs = $authorToNotification = [];
462 while ($row = $statement->fetchArray()) {
463 if ($row['authorID']) {
464 $authorIDs[] = $row['authorID'];
467 if (!isset($authorToNotification[$row['notificationID']])) {
468 $authorToNotification[$row['notificationID']] = [];
471 $authorToNotification[$row['notificationID']][] = $row['authorID'];
475 $authors = UserProfile
::getUserProfiles($authorIDs);
476 $unknownAuthor = new UserProfile(new User(null, ['userID' => null, 'username' => WCF
::getLanguage()->get('wcf.user.guest')]));
478 // load objects associated with each object type
479 foreach ($objectTypes as $objectType => $objectData) {
480 /** @noinspection PhpUndefinedMethodInspection */
481 $objectTypes[$objectType]['objects'] = $objectData['objectType']->getObjectsByIDs($objectData['objectIDs']);
484 // load required events
485 $eventList = new UserNotificationEventList();
486 $eventList->getConditionBuilder()->add("user_notification_event.eventID IN (?)", [$eventIDs]);
487 $eventList->readObjects();
488 $eventObjects = $eventList->getObjects();
490 // build notification data
492 $deleteNotifications = [];
493 foreach ($notificationObjects as $notification) {
494 $object = $objectTypes[$notification->objectType
]['objects'][$notification->objectID
];
495 if ($object->__unknownNotificationObject
) {
496 $deleteNotifications[] = $notification;
500 $className = $eventObjects[$notification->eventID
]->className
;
502 /** @var IUserNotificationEvent $class */
503 $class = new $className($eventObjects[$notification->eventID
]);
507 (isset($authors[$notification->authorID
]) ?
$authors[$notification->authorID
] : $unknownAuthor),
508 $notification->additionalData
511 if (isset($authorToNotification[$notification->notificationID
])) {
513 foreach ($authorToNotification[$notification->notificationID
] as $userID) {
515 $eventAuthors[0] = $unknownAuthor;
517 else if (isset($authors[$userID])) {
518 $eventAuthors[$userID] = $authors[$userID];
521 if (!empty($eventAuthors)) {
522 $class->setAuthors($eventAuthors);
527 'authors' => count($class->getAuthors()),
529 'notificationID' => $notification->notificationID
,
530 'time' => $notification->time
533 $data['confirmed'] = ($notification->confirmTime
> 0);
535 $notifications[] = $data;
539 foreach ($notifications as $index => $notificationData) {
540 /** @var IUserNotificationEvent $event */
541 $event = $notificationData['event'];
542 if (!$event->checkAccess()) {
543 if ($event->deleteNoAccessNotification()) {
544 $deleteNotifications[] = $event->getNotification();
547 unset($notifications[$index]);
551 if (!empty($deleteNotifications)) {
552 $notificationAction = new UserNotificationAction($deleteNotifications, 'delete');
553 $notificationAction->executeAction();
555 // reset notification counter
556 UserStorageHandler
::getInstance()->reset([WCF
::getUser()->userID
], 'userNotificationCount');
560 'count' => count($notifications),
561 'notifications' => $notifications
566 * Returns event object for given object type and event, returns NULL on failure.
568 * @param string $objectType
569 * @param string $eventName
570 * @return IUserNotificationEvent
572 public function getEvent($objectType, $eventName) {
573 if (!isset($this->availableEvents
[$objectType][$eventName])) return null;
575 return $this->availableEvents
[$objectType][$eventName];
579 * Returns all events for given object type.
581 * @param string $objectType
582 * @return IUserNotificationEvent[]
584 public function getEvents($objectType) {
585 if (!isset($this->availableEvents
[$objectType])) return [];
587 return $this->availableEvents
[$objectType];
591 * Retrieves a notification id.
593 * @param integer $eventID
594 * @param integer $objectID
595 * @param integer $authorID
596 * @param integer $time
598 * @throws SystemException
600 public function getNotificationID($eventID, $objectID, $authorID = null, $time = null) {
601 if ($authorID === null && $time === null) {
602 throw new SystemException("authorID and time cannot be omitted at once.");
605 $conditions = new PreparedStatementConditionBuilder();
606 $conditions->add("eventID = ?", [$eventID]);
607 $conditions->add("objectID = ?", [$objectID]);
608 if ($authorID !== null) $conditions->add("authorID = ?", [$authorID]);
609 if ($time !== null) $conditions->add("time = ?", [$time]);
611 $sql = "SELECT notificationID
612 FROM wcf".WCF_N
."_user_notification
614 $statement = WCF
::getDB()->prepareStatement($sql);
615 $statement->execute($conditions->getParameters());
617 $row = $statement->fetchArray();
619 return ($row === false) ?
null : $row['notificationID'];
623 * Returns a list of available object types.
625 * @return IUserNotificationObjectType[]
627 public function getAvailableObjectTypes() {
628 return $this->availableObjectTypes
;
632 * Returns a list of available events.
634 * @return IUserNotificationEvent[][]
636 public function getAvailableEvents() {
637 return $this->availableEvents
;
641 * Returns object type id by name.
643 * @param string $objectType
646 public function getObjectTypeID($objectType) {
647 if (isset($this->objectTypes
[$objectType])) {
648 return $this->objectTypes
[$objectType]->objectTypeID
;
655 * Returns the processor of the object type with the given name or `null`
656 * if no such processor exists
658 * @param string $objectType
659 * @return IUserNotificationObjectType|null
661 public function getObjectTypeProcessor($objectType) {
662 if (isset($this->availableObjectTypes
[$objectType])) {
663 return $this->availableObjectTypes
[$objectType];
670 * Sends the mail notification.
672 * @param UserNotification $notification
674 * @param IUserNotificationEvent $event
676 public function sendInstantMailNotification(UserNotification
$notification, User
$user, IUserNotificationEvent
$event) {
677 // no notifications for disabled or banned users
678 if (!$user->isEmailConfirmed()) return;
679 if ($user->banned
) return;
681 // recipient's language
682 $event->setLanguage($user->getLanguage());
684 // generate token if not present
685 if (!$user->notificationMailToken
) {
686 $token = bin2hex(\random_bytes
(10));
687 $editor = new UserEditor($user);
688 $editor->update(['notificationMailToken' => $token]);
691 $user = new User($user->userID
);
694 $email = new Email();
695 $email->setSubject($user->getLanguage()->getDynamicVariable('wcf.user.notification.mail.subject', [
696 'title' => $event->getEmailTitle()
698 $email->addRecipient(new UserMailbox($user));
699 $humanReadableListId = $user->getLanguage()->getDynamicVariable('wcf.user.notification.'.$event->objectType
.'.'.$event->eventName
);
700 $email->setListID($event->eventName
.'.'.$event->objectType
.'.instant.notification', $humanReadableListId);
701 $email->setListUnsubscribe(LinkHandler
::getInstance()->getControllerLink(NotificationUnsubscribeForm
::class, [
702 // eventID is not part of the parameter list, because we can't communicate that
703 // only a single type would be unsubscribed.
704 // The recipient's expectations when performing the One-Click unsubscribing are that
705 // no further emails will be received. Not following that expectation might result in
707 'userID' => $user->userID
,
708 'token' => $user->notificationMailToken
,
711 $message = $event->getEmailMessage('instant');
712 if (is_array($message)) {
713 if (!isset($message['variables'])) $message['variables'] = [];
714 $variables = array_merge($message['variables'], [
715 'notificationContent' => $message,
717 'notificationType' => 'instant',
718 'variables' => $message['variables'] // deprecated, but is kept for backwards compatibility
721 if (isset($message['message-id'])) {
722 $email->setMessageID($message['message-id']);
724 if (isset($message['in-reply-to'])) {
725 foreach ($message['in-reply-to'] as $inReplyTo) $email->addInReplyTo($inReplyTo);
727 if (isset($message['references'])) {
728 foreach ($message['references'] as $references) $email->addReferences($references);
731 $html = new RecipientAwareTextMimePart('text/html', 'email_notification', 'wcf', $variables);
732 $plainText = new RecipientAwareTextMimePart('text/plain', 'email_notification', 'wcf', $variables);
733 $email->setBody(new MimePartFacade([$html, $plainText]));
736 $email->setBody(new RecipientAwareTextMimePart('text/plain', 'email_notification', 'wcf', [
737 'notificationContent' => $message,
739 'notificationType' => 'instant'
743 $jobs = $email->getJobs();
744 foreach ($jobs as $job) {
745 $wrappedJob = new NotificationEmailDeliveryBackgroundJob($job, $notification, $user);
746 BackgroundQueueHandler
::getInstance()->enqueueIn($wrappedJob);
751 * This method does not delete notifications, instead it marks them as confirmed. The system
752 * does not allow to delete them, but since it was intended in WCF 2.0, this method only
753 * exists for compatibility reasons.
755 * Please consider replacing your calls with markAsConfirmed().
759 * @param string $eventName
760 * @param string $objectType
761 * @param integer[] $recipientIDs
762 * @param integer[] $objectIDs
764 public function deleteNotifications($eventName, $objectType, array $recipientIDs, array $objectIDs = []) {
765 $this->markAsConfirmed($eventName, $objectType, $recipientIDs, $objectIDs);
769 * Removes notifications, this method should only be invoked for delete objects.
771 * @param string $objectType
772 * @param integer[] $objectIDs
773 * @throws SystemException
775 public function removeNotifications($objectType, array $objectIDs) {
776 // check given object type
777 $objectTypeObj = ObjectTypeCache
::getInstance()->getObjectTypeByName('com.woltlab.wcf.notification.objectType', $objectType);
778 if ($objectTypeObj === null) {
779 throw new SystemException("Unknown object type ".$objectType." given");
783 $sql = "SELECT eventID
784 FROM wcf".WCF_N
."_user_notification_event
785 WHERE objectTypeID = ?";
786 $statement = WCF
::getDB()->prepareStatement($sql);
787 $statement->execute([
788 $objectTypeObj->objectTypeID
790 $eventIDs = $statement->fetchAll(\PDO
::FETCH_COLUMN
);
792 if (!empty($eventIDs)) {
793 $conditions = new PreparedStatementConditionBuilder();
794 $conditions->add("eventID IN (?)", [$eventIDs]);
795 $conditions->add("objectID IN (?)", [$objectIDs]);
797 $sql = "SELECT userID
798 FROM wcf".WCF_N
."_user_notification
800 $statement = WCF
::getDB()->prepareStatement($sql);
801 $statement->execute($conditions->getParameters());
802 $userIDs = $statement->fetchAll(\PDO
::FETCH_COLUMN
);
804 // reset number of notifications
805 if (!empty($userIDs)) {
806 UserStorageHandler
::getInstance()->reset(array_unique($userIDs), 'userNotificationCount');
810 'eventIDs' => $eventIDs,
811 'objectIDs' => $objectIDs,
812 'objectType' => $objectType,
813 'userIDs' => $userIDs,
815 EventHandler
::getInstance()->fireAction($this, 'removeNotifications', $parameters);
817 // delete notifications
818 $sql = "DELETE FROM wcf".WCF_N
."_user_notification
820 $statement = WCF
::getDB()->prepareStatement($sql);
821 $statement->execute($conditions->getParameters());
826 * Marks notifications as confirmed
828 * @param string $eventName
829 * @param string $objectType
830 * @param integer[] $recipientIDs
831 * @param integer[] $objectIDs
832 * @throws SystemException
834 public function markAsConfirmed($eventName, $objectType, array $recipientIDs, array $objectIDs = []) {
835 // check given object type and event name
836 if (!isset($this->availableEvents
[$objectType][$eventName])) {
837 throw new SystemException("Unknown event ".$objectType."-".$eventName." given");
841 $event = $this->availableEvents
[$objectType][$eventName];
844 $conditions = new PreparedStatementConditionBuilder();
845 $conditions->add("eventID = ?", [$event->eventID
]);
846 if (!empty($recipientIDs)) $conditions->add("userID IN (?)", [$recipientIDs]);
847 if (!empty($objectIDs)) $conditions->add("objectID IN (?)", [$objectIDs]);
849 $sql = "UPDATE wcf".WCF_N
."_user_notification
852 $statement = WCF
::getDB()->prepareStatement($sql);
853 $parameters = $conditions->getParameters();
854 array_unshift($parameters, TIME_NOW
);
855 $statement->execute($parameters);
859 'eventName' => $eventName,
860 'objectIDs' => $objectIDs,
861 'objectType' => $objectType,
862 'recipientIDs' => $recipientIDs,
864 EventHandler
::getInstance()->fireAction($this, 'markAsConfirmed', $parameters);
866 // delete notification_to_user assignments (mimic legacy notification system)
867 $sql = "DELETE FROM wcf".WCF_N
."_user_notification_to_user
868 WHERE notificationID NOT IN (
869 SELECT notificationID
870 FROM wcf".WCF_N
."_user_notification
871 WHERE confirmTime = ?
873 $statement = WCF
::getDB()->prepareStatement($sql);
874 $statement->execute([0]);
877 if (!empty($recipientIDs)) {
878 UserStorageHandler
::getInstance()->reset($recipientIDs, 'userNotificationCount');
881 UserStorageHandler
::getInstance()->resetAll('userNotificationCount');
886 * Marks a single notification id as confirmed.
888 * @param integer $notificationID
889 * @deprecated 5.2 Please use `UserNotificationHandler::markAsConfirmedByIDs()` instead.
891 public function markAsConfirmedByID($notificationID) {
892 $this->markAsConfirmedByIDs([$notificationID]);
896 * Marks a list of notification ids as confirmed.
898 * @param integer[] $notificationIDs
900 public function markAsConfirmedByIDs(array $notificationIDs) {
901 if (empty($notificationIDs)) {
905 $conditions = new PreparedStatementConditionBuilder();
906 $conditions->add("notificationID IN (?)", [$notificationIDs]);
908 // mark notifications as confirmed
909 $sql = "UPDATE wcf".WCF_N
."_user_notification
912 $statement = WCF
::getDB()->prepareStatement($sql);
913 $parameters = $conditions->getParameters();
914 array_unshift($parameters, TIME_NOW
);
915 $statement->execute($parameters);
917 $parameters = ['notificationIDs' => $notificationIDs];
918 EventHandler
::getInstance()->fireAction($this, 'markAsConfirmedByIDs', $parameters);
920 // delete notification_to_user assignments (mimic legacy notification system)
921 $sql = "DELETE FROM wcf".WCF_N
."_user_notification_to_user
923 $statement = WCF
::getDB()->prepareStatement($sql);
924 $statement->execute($conditions->getParameters());
926 // reset user storage
927 UserStorageHandler
::getInstance()->reset([WCF
::getUser()->userID
], 'userNotificationCount');
931 * Returns the user's notification setting for the given event.
933 * @param string $objectType
934 * @param string $eventName
937 public function getEventSetting($objectType, $eventName) {
939 $event = $this->getEvent($objectType, $eventName);
942 $sql = "SELECT mailNotificationType
943 FROM wcf".WCF_N
."_user_notification_event_to_user
946 $statement = WCF
::getDB()->prepareStatement($sql);
947 $statement->execute([$event->eventID
, WCF
::getUser()->userID
]);
948 $row = $statement->fetchArray();
949 if ($row === false) return false;
950 return $row['mailNotificationType'];
954 * Returns the title and text-only message body for the latest notification,
955 * that is both unread and newer than `$lastRequestTimestamp`. May return an
956 * empty array if there is no new notification.
958 * @param integer $lastRequestTimestamp
961 public function getLatestNotification($lastRequestTimestamp) {
962 $notifications = $this->fetchNotifications(1, 0, 0);
963 if (!empty($notifications) && reset($notifications)->time
> $lastRequestTimestamp) {
964 $notifications = $this->processNotifications($notifications);
966 if (isset($notifications['notifications'][0])) {
967 /** @var IUserNotificationEvent $event */
968 $event = $notifications['notifications'][0]['event'];
971 'title' => strip_tags($event->getTitle()),
972 'message' => strip_tags($event->getMessage()),
973 'link' => LinkHandler
::getInstance()->getLink('NotificationConfirm', ['id' => $event->getNotification()->notificationID
])