3 * @copyright Copyright (C) 2010-2022, 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;
30 use Friendica\Database\DBStructure;
32 use Friendica\Model\Contact;
33 use Friendica\Model\Post;
34 use Friendica\Model\Subscription;
35 use Friendica\Model\Tag;
36 use Friendica\Navigation\Notifications;
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;
55 * Insert a new user notification entry
57 * @param integer $uri_id
60 * @return bool success
63 public static function insert(int $uri_id, int $uid, array $data = []): bool
66 throw new BadMethodCallException('Empty URI_id');
69 $fields = DBStructure::getFieldsForTable('post-user-notification', $data);
71 $fields['uri-id'] = $uri_id;
72 $fields['uid'] = $uid;
74 return DBA::insert('post-user-notification', $fields, Database::INSERT_IGNORE);
78 * Update a user notification entry
80 * @param integer $uri_id
83 * @param bool $insert_if_missing
87 public static function update(int $uri_id, int $uid, array $data = [], bool $insert_if_missing = false): bool
90 throw new BadMethodCallException('Empty URI_id');
93 $fields = DBStructure::getFieldsForTable('post-user-notification', $data);
95 // Remove the key fields
96 unset($fields['uri-id']);
97 unset($fields['uid']);
103 return DBA::update('post-user-notification', $fields, ['uri-id' => $uri_id, 'uid' => $uid], $insert_if_missing ? true : []);
107 * Delete a row from the post-user-notification table
109 * @param array $conditions Field condition(s)
110 * @param array $options - cascade: If true we delete records in other tables that depend on the one we're deleting through
111 * relations (default: true)
113 * @return boolean was the deletion successful?
116 public static function delete(array $conditions, array $options = []): bool
118 return DBA::delete('post-user-notification', $conditions, $options);
122 * Checks an item for notifications and sets the "notification-type" field
125 * - Check for mentions in posts with "uid=0" where the user hadn't interacted before
127 * @param int $uri_id URI ID
128 * @param int $uid user ID
131 public static function setNotification(int $uri_id, int $uid)
133 $fields = ['id', 'uri-id', 'parent-uri-id', 'uid', 'body', 'parent', 'gravity', 'vid', 'gravity',
134 'private', 'contact-id', 'thr-parent', 'thr-parent-id', 'parent-uri-id', 'parent-uri', 'author-id', 'verb'];
135 $item = Post::selectFirst($fields, ['uri-id' => $uri_id, 'uid' => $uid, 'origin' => false]);
136 if (!DBA::isResult($item)) {
140 // "Activity::FOLLOW" is an automated activity, so we ignore it here
141 if ($item['verb'] == Activity::FOLLOW) {
145 if ($item['uid'] == 0) {
148 // Always include the item user
149 $uids = [$item['uid']];
152 // Add every user who participated so far in this thread
153 // This can only happen with participations on global items. (means: uid = 0)
154 $users = DBA::p("SELECT DISTINCT(`contact-uid`) AS `uid` FROM `post-user-view`
155 WHERE `contact-uid` != 0 AND `parent-uri-id` = ? AND `uid` = ?", $item['parent-uri-id'], $uid);
156 while ($user = DBA::fetch($users)) {
157 $uids[] = $user['uid'];
161 foreach (array_unique($uids) as $uid) {
162 self::setNotificationForUser($item, $uid);
167 * Checks an item for notifications for the given user and sets the "notification-type" field
169 * @param array $item Item array
170 * @param int $uid User ID
171 * @throws HTTPException\InternalServerErrorException
173 private static function setNotificationForUser(array $item, int $uid)
175 if (Post\ThreadUser::getIgnored($item['parent-uri-id'], $uid)) {
179 $notification_type = self::TYPE_NONE;
181 if (self::checkShared($item, $uid)) {
182 $notification_type = $notification_type | self::TYPE_SHARED;
183 self::insertNotificationByItem(self::TYPE_SHARED, $uid, $item);
189 $profiles = self::getProfileForUser($uid);
191 // Fetch all contacts for the given profiles
194 $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
195 while ($contact = DBA::fetch($ret)) {
196 $contacts[] = $contact['id'];
200 // Don't create notifications for user's posts
201 if (in_array($item['author-id'], $contacts)) {
205 if (self::checkExplicitMention($item, $profiles)) {
206 $notification_type = $notification_type | self::TYPE_EXPLICIT_TAGGED;
208 self::insertNotificationByItem(self::TYPE_EXPLICIT_TAGGED, $uid, $item);
213 if (self::checkImplicitMention($item, $profiles)) {
214 $notification_type = $notification_type | self::TYPE_IMPLICIT_TAGGED;
216 self::insertNotificationByItem(self::TYPE_IMPLICIT_TAGGED, $uid, $item);
221 if (self::checkDirectComment($item, $contacts)) {
222 $notification_type = $notification_type | self::TYPE_DIRECT_COMMENT;
224 self::insertNotificationByItem(self::TYPE_DIRECT_COMMENT, $uid, $item);
229 if (self::checkDirectCommentedThread($item, $contacts)) {
230 $notification_type = $notification_type | self::TYPE_DIRECT_THREAD_COMMENT;
232 self::insertNotificationByItem(self::TYPE_DIRECT_THREAD_COMMENT, $uid, $item);
237 if (self::checkCommentedThread($item, $contacts)) {
238 $notification_type = $notification_type | self::TYPE_THREAD_COMMENT;
240 self::insertNotificationByItem(self::TYPE_THREAD_COMMENT, $uid, $item);
245 if (self::checkCommentedParticipation($item, $contacts)) {
246 $notification_type = $notification_type | self::TYPE_COMMENT_PARTICIPATION;
248 self::insertNotificationByItem(self::TYPE_COMMENT_PARTICIPATION, $uid, $item);
253 if (self::checkActivityParticipation($item, $contacts)) {
254 $notification_type = $notification_type | self::TYPE_ACTIVITY_PARTICIPATION;
256 self::insertNotificationByItem(self::TYPE_ACTIVITY_PARTICIPATION, $uid, $item);
260 if (empty($notification_type)) {
264 // Only create notifications for posts and comments, not for activities
265 if (($item['gravity'] == GRAVITY_ACTIVITY) && ($item['verb'] != Activity::ANNOUNCE)) {
269 Logger::info('Set notification', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'notification-type' => $notification_type]);
271 $fields = ['notification-type' => $notification_type];
272 Post\User::update($item['uri-id'], $uid, $fields);
273 self::update($item['uri-id'], $uid, $fields, true);
277 * Add a notification entry for a given item array
279 * @param int $type User notification type
280 * @param int $uid User ID
281 * @param array $item Item array
285 private static function insertNotificationByItem(int $type, int $uid, array $item): void
287 if (($item['verb'] != Activity::ANNOUNCE) && ($item['gravity'] == GRAVITY_ACTIVITY) &&
288 !in_array($type, [self::TYPE_DIRECT_COMMENT, self::TYPE_DIRECT_THREAD_COMMENT])) {
289 // Activities are only stored when performed on the user's post or comment
293 $notification = (new Notifications\Factory\Notification(DI::logger()))->createForUser(
298 $item['gravity'] == GRAVITY_ACTIVITY ? $item['thr-parent-id'] : $item['uri-id'],
299 $item['parent-uri-id']
303 $notification = DI::notification()->save($notification);
304 Subscription::pushByNotification($notification);
305 } catch (Exception $e) {
311 * Add a notification entry
313 * @param int $actor Contact ID of the actor
314 * @param string $verb One of the Activity verb constant values
315 * @param int $uid User ID
319 public static function insertNotification(int $actor, string $verb, int $uid): bool
321 $notification = (new Notifications\Factory\Notification(DI::logger()))->createForRelationship(
327 $notification = DI::notification()->save($notification);
328 Subscription::pushByNotification($notification);
330 } catch (Exception $e) {
336 * Fetch all profiles (contact URL) of a given user
338 * @param int $uid User ID
340 * @return array Profile links
341 * @throws HTTPException\InternalServerErrorException
343 private static function getProfileForUser(int $uid): array
345 $notification_data = ['uid' => $uid, 'profiles' => []];
346 Hook::callAll('check_item_notification', $notification_data);
348 $profiles = $notification_data['profiles'];
350 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
351 if (!DBA::isResult($user)) {
355 $owner = DBA::selectFirst('contact', ['url', 'alias'], ['self' => true, 'uid' => $uid]);
356 if (!DBA::isResult($owner)) {
360 // This is our regular URL format
361 $profiles[] = $owner['url'];
364 $profiles[] = $owner['alias'];
366 // Notifications from Diaspora often have a URL in the Diaspora format
367 $profiles[] = DI::baseUrl() . '/u/' . $user['nickname'];
369 // Validate and add profile links
370 foreach ($profiles as $key => $profile) {
371 // Check for invalid profile urls (without scheme, host or path) and remove them
372 if (empty(parse_url($profile, PHP_URL_SCHEME)) || empty(parse_url($profile, PHP_URL_HOST)) || empty(parse_url($profile, PHP_URL_PATH))) {
373 unset($profiles[$key]);
377 // Add the normalized form
378 $profile = Strings::normaliseLink($profile);
379 $profiles[] = $profile;
382 $profile = str_replace('http://', 'https://', $profile);
383 $profiles[] = $profile;
386 return array_unique($profiles);
390 * Check for a "shared" notification for every new post of contacts from the given user
393 * @param int $uid User ID
394 * @return bool A contact had shared something
397 private static function checkShared(array $item, int $uid): bool
399 // Only check on original posts and reshare ("announce") activities, otherwise return
400 if (($item['gravity'] != GRAVITY_PARENT) && ($item['verb'] != Activity::ANNOUNCE)) {
404 // Check if the contact posted or shared something directly
405 if (DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true])) {
413 * Check for an implicit mention (only in tags, not in body) of the given user
416 * @param array $profiles Profile links
417 * @return bool The user is mentioned
420 private static function checkImplicitMention(array $item, array $profiles): bool
422 $mentions = Tag::getByURIId($item['uri-id'], [Tag::IMPLICIT_MENTION]);
423 foreach ($mentions as $mention) {
424 foreach ($profiles as $profile) {
425 if (Strings::compareLink($profile, $mention['url'])) {
435 * Check for an explicit mention (tag and body) of the given user
438 * @param array $profiles Profile links
439 * @return bool The user is mentioned
442 private static function checkExplicitMention(array $item, array $profiles): bool
444 $mentions = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
445 foreach ($mentions as $mention) {
446 foreach ($profiles as $profile) {
447 if (Strings::compareLink($profile, $mention['url'])) {
457 * Check if the given user had created this thread
460 * @param array $contacts Array of contact IDs
461 * @return bool The user had created this thread
464 private static function checkCommentedThread(array $item, array $contacts): bool
466 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_PARENT];
467 return Post::exists($condition);
471 * Check for a direct comment to a post of the given user
474 * @param array $contacts Array of contact IDs
475 * @return bool The item is a direct comment to a user comment
478 private static function checkDirectComment(array $item, array $contacts): bool
480 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_COMMENT];
481 return Post::exists($condition);
485 * Check for a direct comment to the starting post of the given user
488 * @param array $contacts Array of contact IDs
489 * @return bool The user had created this thread
492 private static function checkDirectCommentedThread(array $item, array $contacts): bool
494 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_PARENT];
495 return Post::exists($condition);
499 * Check if the user had commented in this thread
502 * @param array $contacts Array of contact IDs
503 * @return bool The user had commented in the thread
506 private static function checkCommentedParticipation(array $item, array $contacts): bool
508 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_COMMENT];
509 return Post::exists($condition);
513 * Check if the user had interacted in this thread (Like, Dislike, ...)
516 * @param array $contacts Array of contact IDs
517 * @return bool The user had interacted in the thread
520 private static function checkActivityParticipation(array $item, array $contacts): bool
522 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY];
523 return Post::exists($condition);