3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model\Post;
24 use BadMethodCallException;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Database\Database;
29 use Friendica\Database\DBA;
31 use Friendica\Model\Contact;
32 use Friendica\Model\Item;
33 use Friendica\Model\Post;
34 use Friendica\Model\Subscription;
35 use Friendica\Model\Tag;
36 use Friendica\Model\User;
37 use Friendica\Network\HTTPException;
38 use Friendica\Protocol\Activity;
39 use Friendica\Util\Strings;
41 class UserNotification
45 const TYPE_EXPLICIT_TAGGED = 1;
46 const TYPE_IMPLICIT_TAGGED = 2;
47 const TYPE_THREAD_COMMENT = 4;
48 const TYPE_DIRECT_COMMENT = 8;
49 const TYPE_COMMENT_PARTICIPATION = 16;
50 const TYPE_ACTIVITY_PARTICIPATION = 32;
51 const TYPE_DIRECT_THREAD_COMMENT = 64;
52 const TYPE_SHARED = 128;
53 const TYPE_FOLLOW = 256;
54 const TYPE_QUOTED = 512;
57 * Insert a new user notification entry
59 * @param integer $uri_id
62 * @return bool success
65 public static function insert(int $uri_id, int $uid, array $data = []): bool
68 throw new BadMethodCallException('Empty URI_id');
71 $fields = DI::dbaDefinition()->truncateFieldsForTable('post-user-notification', $data);
73 $fields['uri-id'] = $uri_id;
74 $fields['uid'] = $uid;
76 return DBA::insert('post-user-notification', $fields, Database::INSERT_IGNORE);
80 * Update a user notification entry
82 * @param integer $uri_id
85 * @param bool $insert_if_missing
89 public static function update(int $uri_id, int $uid, array $data = [], bool $insert_if_missing = false): bool
92 throw new BadMethodCallException('Empty URI_id');
95 $fields = DI::dbaDefinition()->truncateFieldsForTable('post-user-notification', $data);
97 // Remove the key fields
98 unset($fields['uri-id']);
99 unset($fields['uid']);
101 if (empty($fields)) {
105 return DBA::update('post-user-notification', $fields, ['uri-id' => $uri_id, 'uid' => $uid], $insert_if_missing ? true : []);
109 * Delete a row from the post-user-notification table
111 * @param array $conditions Field condition(s)
112 * @param array $options - cascade: If true we delete records in other tables that depend on the one we're deleting through
113 * relations (default: true)
115 * @return boolean was the deletion successful?
118 public static function delete(array $conditions, array $options = []): bool
120 return DBA::delete('post-user-notification', $conditions, $options);
124 * Checks an item for notifications and sets the "notification-type" field
127 * - Check for mentions in posts with "uid=0" where the user hadn't interacted before
129 * @param int $uri_id URI ID
130 * @param int $uid user ID
133 public static function setNotification(int $uri_id, int $uid)
135 $fields = ['id', 'uri-id', 'parent-uri-id', 'uid', 'body', 'parent', 'gravity', 'vid', 'gravity',
136 'contact-id', 'author-id', 'owner-id', 'causer-id',
137 'private', 'thr-parent', 'thr-parent-id', 'parent-uri-id', 'parent-uri', 'verb'];
138 $item = Post::selectFirst($fields, ['uri-id' => $uri_id, 'uid' => $uid, 'origin' => false]);
139 if (!DBA::isResult($item)) {
143 $parent = Post::selectFirstPost(['author-id', 'owner-id', 'causer-id'], ['uri-id' => $item['parent-uri-id']]);
144 if (!DBA::isResult($parent)) {
148 // "Activity::FOLLOW" is an automated activity, so we ignore it here
149 if ($item['verb'] == Activity::FOLLOW) {
153 if ($item['uid'] == 0) {
156 // Always include the item user
157 $uids = [$item['uid']];
160 // Add every user who participated so far in this thread
161 // This can only happen with participations on global items. (means: uid = 0)
162 $users = DBA::p("SELECT DISTINCT(`contact-uid`) AS `uid` FROM `post-user-view`
163 WHERE `contact-uid` != 0 AND `parent-uri-id` = ? AND `uid` = ?", $item['parent-uri-id'], $uid);
164 while ($user = DBA::fetch($users)) {
165 $uids[] = $user['uid'];
169 foreach (array_unique($uids) as $uid) {
170 self::setNotificationForUser($item, $parent, $uid);
175 * Checks an item for notifications for the given user and sets the "notification-type" field
177 * @param array $item Item array
178 * @param array $parent Parent item array
179 * @param int $uid User ID
180 * @throws HTTPException\InternalServerErrorException
182 private static function setNotificationForUser(array $item, array $parent, int $uid)
184 if (Post\ThreadUser::getIgnored($item['parent-uri-id'], $uid)) {
188 foreach (array_unique([$parent['author-id'], $parent['owner-id'], $parent['causer-id'], $item['author-id'], $item['owner-id'], $item['causer-id']]) as $author_id) {
189 if (empty($author_id)) {
192 if (Contact\User::isBlocked($author_id, $uid) || Contact\User::isIgnored($author_id, $uid) || Contact\User::isCollapsed($author_id, $uid)) {
193 Logger::debug('Author is blocked/ignored/collapsed by user', ['uid' => $uid, 'author' => $author_id, 'uri-id' => $item['uri-id']]);
198 $user = User::getById($uid, ['account-type', 'account_removed', 'account_expired']);
199 if (in_array($user['account-type'], [User::ACCOUNT_TYPE_COMMUNITY, User::ACCOUNT_TYPE_RELAY])) {
203 if ($user['account_removed'] || $user['account_expired']) {
207 $author = Contact::getById($item['author-id'], ['contact-type']);
208 if (empty($author)) {
212 $notification_type = self::TYPE_NONE;
214 if (self::checkShared($item, $uid)) {
215 $notification_type = $notification_type | self::TYPE_SHARED;
216 self::insertNotificationByItem(self::TYPE_SHARED, $uid, $item);
218 } elseif ($author['contact-type'] == Contact::TYPE_COMMUNITY) {
224 $profiles = self::getProfileForUser($uid);
226 // Fetch all contacts for the given profiles
228 $iscommunity = false;
230 $ret = DBA::select('contact', ['id', 'contact-type'], ['uid' => 0, 'nurl' => $profiles]);
231 while ($contact = DBA::fetch($ret)) {
232 $contacts[] = $contact['id'];
234 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
240 // Don't create notifications for user's posts
241 if (in_array($item['author-id'], $contacts)) {
245 if (($item['verb'] != Activity::ANNOUNCE) && self::checkExplicitMention($item, $profiles)) {
246 $notification_type = $notification_type | self::TYPE_EXPLICIT_TAGGED;
248 self::insertNotificationByItem(self::TYPE_EXPLICIT_TAGGED, $uid, $item);
253 if (($item['verb'] != Activity::ANNOUNCE) && self::checkImplicitMention($item, $profiles)) {
254 $notification_type = $notification_type | self::TYPE_IMPLICIT_TAGGED;
256 self::insertNotificationByItem(self::TYPE_IMPLICIT_TAGGED, $uid, $item);
261 if (self::checkDirectComment($item, $contacts)) {
262 $notification_type = $notification_type | self::TYPE_DIRECT_COMMENT;
264 self::insertNotificationByItem(self::TYPE_DIRECT_COMMENT, $uid, $item);
269 if (!$iscommunity && self::checkDirectCommentedThread($item, $contacts)) {
270 $notification_type = $notification_type | self::TYPE_DIRECT_THREAD_COMMENT;
272 self::insertNotificationByItem(self::TYPE_DIRECT_THREAD_COMMENT, $uid, $item);
277 if (($item['verb'] != Activity::ANNOUNCE) && self::checkCommentedThread($item, $contacts)) {
278 $notification_type = $notification_type | self::TYPE_THREAD_COMMENT;
280 self::insertNotificationByItem(self::TYPE_THREAD_COMMENT, $uid, $item);
285 if (($item['verb'] != Activity::ANNOUNCE) && self::checkCommentedParticipation($item, $contacts)) {
286 $notification_type = $notification_type | self::TYPE_COMMENT_PARTICIPATION;
288 self::insertNotificationByItem(self::TYPE_COMMENT_PARTICIPATION, $uid, $item);
293 if (($item['verb'] != Activity::ANNOUNCE) && self::checkQuoted($item, $contacts)) {
294 $notification_type = $notification_type | self::TYPE_QUOTED;
296 self::insertNotificationByItem(self::TYPE_QUOTED, $uid, $item);
301 if (($item['verb'] != Activity::ANNOUNCE) && self::checkFollowParticipation($item, $contacts)) {
302 $notification_type = $notification_type | self::TYPE_FOLLOW;
304 self::insertNotificationByItem(self::TYPE_FOLLOW, $uid, $item);
309 if (($item['verb'] != Activity::ANNOUNCE) && self::checkActivityParticipation($item, $contacts)) {
310 $notification_type = $notification_type | self::TYPE_ACTIVITY_PARTICIPATION;
312 self::insertNotificationByItem(self::TYPE_ACTIVITY_PARTICIPATION, $uid, $item);
316 if (empty($notification_type)) {
320 // Only create notifications for posts and comments, not for activities
321 if (($item['gravity'] == Item::GRAVITY_ACTIVITY) && ($item['verb'] != Activity::ANNOUNCE)) {
325 Logger::info('Set notification', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'notification-type' => $notification_type]);
327 $fields = ['notification-type' => $notification_type];
328 Post\User::update($item['uri-id'], $uid, $fields);
329 self::update($item['uri-id'], $uid, $fields, true);
333 * Add a notification entry for a given item array
335 * @param int $type User notification type
336 * @param int $uid User ID
337 * @param array $item Item array
341 private static function insertNotificationByItem(int $type, int $uid, array $item): void
343 if (($item['verb'] != Activity::ANNOUNCE) && ($item['gravity'] == Item::GRAVITY_ACTIVITY) &&
344 !in_array($type, [self::TYPE_DIRECT_COMMENT, self::TYPE_DIRECT_THREAD_COMMENT])) {
345 // Activities are only stored when performed on the user's post or comment
349 $notification = DI::notificationFactory()->createForUser(
354 $item['gravity'] == Item::GRAVITY_ACTIVITY ? $item['thr-parent-id'] : $item['uri-id'],
355 $item['parent-uri-id']
359 $notification = DI::notification()->save($notification);
360 Subscription::pushByNotification($notification);
361 } catch (Exception $e) {
367 * Add a notification entry
369 * @param int $actor Public contact ID of the actor
370 * @param string $verb One of the Activity verb constant values
371 * @param int $uid User ID
375 public static function insertNotification(int $actor, string $verb, int $uid): bool
377 $notification = DI::notificationFactory()->createForRelationship(
383 $notification = DI::notification()->save($notification);
384 Subscription::pushByNotification($notification);
386 } catch (Exception $e) {
392 * Fetch all profiles (contact URL) of a given user
394 * @param int $uid User ID
396 * @return array Profile links
397 * @throws HTTPException\InternalServerErrorException
399 private static function getProfileForUser(int $uid): array
401 $notification_data = ['uid' => $uid, 'profiles' => []];
402 Hook::callAll('check_item_notification', $notification_data);
404 $profiles = $notification_data['profiles'];
406 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
407 if (!DBA::isResult($user)) {
411 $owner = DBA::selectFirst('contact', ['url', 'alias'], ['self' => true, 'uid' => $uid]);
412 if (!DBA::isResult($owner)) {
416 // This is our regular URL format
417 $profiles[] = $owner['url'];
420 $profiles[] = $owner['alias'];
422 // Notifications from Diaspora often have a URL in the Diaspora format
423 $profiles[] = DI::baseUrl() . '/u/' . $user['nickname'];
425 // Validate and add profile links
426 foreach ($profiles as $key => $profile) {
427 // Check for invalid profile urls (without scheme, host or path) and remove them
428 if (empty(parse_url($profile, PHP_URL_SCHEME)) || empty(parse_url($profile, PHP_URL_HOST)) || empty(parse_url($profile, PHP_URL_PATH))) {
429 unset($profiles[$key]);
433 // Add the normalized form
434 $profile = Strings::normaliseLink($profile);
435 $profiles[] = $profile;
438 $profile = str_replace('http://', 'https://', $profile);
439 $profiles[] = $profile;
442 return array_unique($profiles);
446 * Check for a "shared" notification for every new post of contacts from the given user
449 * @param int $uid User ID
450 * @return bool A contact had shared something
453 private static function checkShared(array $item, int $uid): bool
455 // Only check on original posts and reshare ("announce") activities, otherwise return
456 if (($item['gravity'] != Item::GRAVITY_PARENT) && ($item['verb'] != Activity::ANNOUNCE)) {
460 // Don't notify about reshares by communities of our own posts or each time someone comments
461 if (($item['verb'] == Activity::ANNOUNCE) && DBA::exists('contact', ['id' => $item['contact-id'], 'contact-type' => Contact::TYPE_COMMUNITY])) {
462 $post = Post::selectFirst(['origin', 'gravity'], ['uri-id' => $item['thr-parent-id'], 'uid' => $uid]);
463 if (!$post || $post['origin'] || ($post['gravity'] != Item::GRAVITY_PARENT)) {
468 // Only check on posts by the user itself
469 $cdata = Contact::getPublicAndUserContactID($item['contact-id'], $item['uid']);
470 if (empty($cdata['user']) || ($item['author-id'] != $cdata['public'])) {
474 // Check if the contact posted or shared something directly
475 if (DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true])) {
483 * Check for an implicit mention (only in tags, not in body) of the given user
486 * @param array $profiles Profile links
487 * @return bool The user is mentioned
490 private static function checkImplicitMention(array $item, array $profiles): bool
492 $mentions = Tag::getByURIId($item['uri-id'], [Tag::IMPLICIT_MENTION]);
493 foreach ($mentions as $mention) {
494 foreach ($profiles as $profile) {
495 if (Strings::compareLink($profile, $mention['url'])) {
505 * Check for an explicit mention (tag and body) of the given user
508 * @param array $profiles Profile links
509 * @return bool The user is mentioned
512 private static function checkExplicitMention(array $item, array $profiles): bool
514 $mentions = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
515 foreach ($mentions as $mention) {
516 foreach ($profiles as $profile) {
517 if (Strings::compareLink($profile, $mention['url'])) {
527 * Check if the given user had created this thread
530 * @param array $contacts Array of contact IDs
531 * @return bool The user had created this thread
534 private static function checkCommentedThread(array $item, array $contacts): bool
536 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_PARENT];
537 return Post::exists($condition);
541 * Check for a direct comment to a post of the given user
544 * @param array $contacts Array of contact IDs
545 * @return bool The item is a direct comment to a user comment
548 private static function checkDirectComment(array $item, array $contacts): bool
550 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_COMMENT];
551 return Post::exists($condition);
555 * Check for a direct comment to the starting post of the given user
558 * @param array $contacts Array of contact IDs
559 * @return bool The user had created this thread
562 private static function checkDirectCommentedThread(array $item, array $contacts): bool
564 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_PARENT];
565 return Post::exists($condition);
569 * Check if the user had commented in this thread
572 * @param array $contacts Array of contact IDs
573 * @return bool The user had commented in the thread
576 private static function checkCommentedParticipation(array $item, array $contacts): bool
578 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_COMMENT];
579 return Post::exists($condition);
583 * Check if the user follows this thread
586 * @param array $contacts Array of contact IDs
587 * @return bool The user follows the thread
590 private static function checkFollowParticipation(array $item, array $contacts): bool
592 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_ACTIVITY, 'verb' => Activity::FOLLOW];
593 return Post::exists($condition);
597 * Check if the user had interacted in this thread (Like, Dislike, ...)
600 * @param array $contacts Array of contact IDs
601 * @return bool The user had interacted in the thread
604 private static function checkActivityParticipation(array $item, array $contacts): bool
606 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_ACTIVITY];
607 return Post::exists($condition);
611 * Check for a quoted post of a post of the given user
614 * @param array $contacts Array of contact IDs
615 * @return bool The item is a quoted post of a user's post or comment
618 private static function checkQuoted(array $item, array $contacts): bool
620 if (empty($item['quote-uri-id'])) {
623 $condition = ['uri-id' => $item['quote-uri-id'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => [item::GRAVITY_PARENT, Item::GRAVITY_COMMENT]];
624 return Post::exists($condition);