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\Model\User;
37 use Friendica\Navigation\Notifications;
38 use Friendica\Network\HTTPException;
39 use Friendica\Protocol\Activity;
40 use Friendica\Util\Strings;
42 class UserNotification
46 const TYPE_EXPLICIT_TAGGED = 1;
47 const TYPE_IMPLICIT_TAGGED = 2;
48 const TYPE_THREAD_COMMENT = 4;
49 const TYPE_DIRECT_COMMENT = 8;
50 const TYPE_COMMENT_PARTICIPATION = 16;
51 const TYPE_ACTIVITY_PARTICIPATION = 32;
52 const TYPE_DIRECT_THREAD_COMMENT = 64;
53 const TYPE_SHARED = 128;
56 * Insert a new user notification entry
58 * @param integer $uri_id
61 * @return bool success
64 public static function insert(int $uri_id, int $uid, array $data = []): bool
67 throw new BadMethodCallException('Empty URI_id');
70 $fields = DBStructure::getFieldsForTable('post-user-notification', $data);
72 $fields['uri-id'] = $uri_id;
73 $fields['uid'] = $uid;
75 return DBA::insert('post-user-notification', $fields, Database::INSERT_IGNORE);
79 * Update a user notification entry
81 * @param integer $uri_id
84 * @param bool $insert_if_missing
88 public static function update(int $uri_id, int $uid, array $data = [], bool $insert_if_missing = false): bool
91 throw new BadMethodCallException('Empty URI_id');
94 $fields = DBStructure::getFieldsForTable('post-user-notification', $data);
96 // Remove the key fields
97 unset($fields['uri-id']);
98 unset($fields['uid']);
100 if (empty($fields)) {
104 return DBA::update('post-user-notification', $fields, ['uri-id' => $uri_id, 'uid' => $uid], $insert_if_missing ? true : []);
108 * Delete a row from the post-user-notification table
110 * @param array $conditions Field condition(s)
111 * @param array $options - cascade: If true we delete records in other tables that depend on the one we're deleting through
112 * relations (default: true)
114 * @return boolean was the deletion successful?
117 public static function delete(array $conditions, array $options = []): bool
119 return DBA::delete('post-user-notification', $conditions, $options);
123 * Checks an item for notifications and sets the "notification-type" field
126 * - Check for mentions in posts with "uid=0" where the user hadn't interacted before
128 * @param int $uri_id URI ID
129 * @param int $uid user ID
132 public static function setNotification(int $uri_id, int $uid)
134 $fields = ['id', 'uri-id', 'parent-uri-id', 'uid', 'body', 'parent', 'gravity', 'vid', 'gravity',
135 'private', 'contact-id', 'thr-parent', 'thr-parent-id', 'parent-uri-id', 'parent-uri', 'author-id', 'verb'];
136 $item = Post::selectFirst($fields, ['uri-id' => $uri_id, 'uid' => $uid, 'origin' => false]);
137 if (!DBA::isResult($item)) {
141 // "Activity::FOLLOW" is an automated activity, so we ignore it here
142 if ($item['verb'] == Activity::FOLLOW) {
146 if ($item['uid'] == 0) {
149 // Always include the item user
150 $uids = [$item['uid']];
153 // Add every user who participated so far in this thread
154 // This can only happen with participations on global items. (means: uid = 0)
155 $users = DBA::p("SELECT DISTINCT(`contact-uid`) AS `uid` FROM `post-user-view`
156 WHERE `contact-uid` != 0 AND `parent-uri-id` = ? AND `uid` = ?", $item['parent-uri-id'], $uid);
157 while ($user = DBA::fetch($users)) {
158 $uids[] = $user['uid'];
162 foreach (array_unique($uids) as $uid) {
163 self::setNotificationForUser($item, $uid);
168 * Checks an item for notifications for the given user and sets the "notification-type" field
170 * @param array $item Item array
171 * @param int $uid User ID
172 * @throws HTTPException\InternalServerErrorException
174 private static function setNotificationForUser(array $item, int $uid)
176 if (Post\ThreadUser::getIgnored($item['parent-uri-id'], $uid)) {
180 $user = User::getById($uid, ['account-type']);
181 if (in_array($user['account-type'], [User::ACCOUNT_TYPE_COMMUNITY, User::ACCOUNT_TYPE_RELAY])) {
185 $notification_type = self::TYPE_NONE;
187 if (self::checkShared($item, $uid)) {
188 $notification_type = $notification_type | self::TYPE_SHARED;
189 self::insertNotificationByItem(self::TYPE_SHARED, $uid, $item);
195 $profiles = self::getProfileForUser($uid);
197 // Fetch all contacts for the given profiles
200 $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
201 while ($contact = DBA::fetch($ret)) {
202 $contacts[] = $contact['id'];
206 // Don't create notifications for user's posts
207 if (in_array($item['author-id'], $contacts)) {
211 if (self::checkExplicitMention($item, $profiles)) {
212 $notification_type = $notification_type | self::TYPE_EXPLICIT_TAGGED;
214 self::insertNotificationByItem(self::TYPE_EXPLICIT_TAGGED, $uid, $item);
219 if (self::checkImplicitMention($item, $profiles)) {
220 $notification_type = $notification_type | self::TYPE_IMPLICIT_TAGGED;
222 self::insertNotificationByItem(self::TYPE_IMPLICIT_TAGGED, $uid, $item);
227 if (self::checkDirectComment($item, $contacts)) {
228 $notification_type = $notification_type | self::TYPE_DIRECT_COMMENT;
230 self::insertNotificationByItem(self::TYPE_DIRECT_COMMENT, $uid, $item);
235 if (self::checkDirectCommentedThread($item, $contacts)) {
236 $notification_type = $notification_type | self::TYPE_DIRECT_THREAD_COMMENT;
238 self::insertNotificationByItem(self::TYPE_DIRECT_THREAD_COMMENT, $uid, $item);
243 if (self::checkCommentedThread($item, $contacts)) {
244 $notification_type = $notification_type | self::TYPE_THREAD_COMMENT;
246 self::insertNotificationByItem(self::TYPE_THREAD_COMMENT, $uid, $item);
251 if (self::checkCommentedParticipation($item, $contacts)) {
252 $notification_type = $notification_type | self::TYPE_COMMENT_PARTICIPATION;
254 self::insertNotificationByItem(self::TYPE_COMMENT_PARTICIPATION, $uid, $item);
259 if (self::checkActivityParticipation($item, $contacts)) {
260 $notification_type = $notification_type | self::TYPE_ACTIVITY_PARTICIPATION;
262 self::insertNotificationByItem(self::TYPE_ACTIVITY_PARTICIPATION, $uid, $item);
266 if (empty($notification_type)) {
270 // Only create notifications for posts and comments, not for activities
271 if (($item['gravity'] == GRAVITY_ACTIVITY) && ($item['verb'] != Activity::ANNOUNCE)) {
275 Logger::info('Set notification', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'notification-type' => $notification_type]);
277 $fields = ['notification-type' => $notification_type];
278 Post\User::update($item['uri-id'], $uid, $fields);
279 self::update($item['uri-id'], $uid, $fields, true);
283 * Add a notification entry for a given item array
285 * @param int $type User notification type
286 * @param int $uid User ID
287 * @param array $item Item array
291 private static function insertNotificationByItem(int $type, int $uid, array $item): void
293 if (($item['verb'] != Activity::ANNOUNCE) && ($item['gravity'] == GRAVITY_ACTIVITY) &&
294 !in_array($type, [self::TYPE_DIRECT_COMMENT, self::TYPE_DIRECT_THREAD_COMMENT])) {
295 // Activities are only stored when performed on the user's post or comment
299 $notification = (new Notifications\Factory\Notification(DI::logger()))->createForUser(
304 $item['gravity'] == GRAVITY_ACTIVITY ? $item['thr-parent-id'] : $item['uri-id'],
305 $item['parent-uri-id']
309 $notification = DI::notification()->save($notification);
310 Subscription::pushByNotification($notification);
311 } catch (Exception $e) {
317 * Add a notification entry
319 * @param int $actor Contact ID of the actor
320 * @param string $verb One of the Activity verb constant values
321 * @param int $uid User ID
325 public static function insertNotification(int $actor, string $verb, int $uid): bool
327 $notification = (new Notifications\Factory\Notification(DI::logger()))->createForRelationship(
333 $notification = DI::notification()->save($notification);
334 Subscription::pushByNotification($notification);
336 } catch (Exception $e) {
342 * Fetch all profiles (contact URL) of a given user
344 * @param int $uid User ID
346 * @return array Profile links
347 * @throws HTTPException\InternalServerErrorException
349 private static function getProfileForUser(int $uid): array
351 $notification_data = ['uid' => $uid, 'profiles' => []];
352 Hook::callAll('check_item_notification', $notification_data);
354 $profiles = $notification_data['profiles'];
356 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
357 if (!DBA::isResult($user)) {
361 $owner = DBA::selectFirst('contact', ['url', 'alias'], ['self' => true, 'uid' => $uid]);
362 if (!DBA::isResult($owner)) {
366 // This is our regular URL format
367 $profiles[] = $owner['url'];
370 $profiles[] = $owner['alias'];
372 // Notifications from Diaspora often have a URL in the Diaspora format
373 $profiles[] = DI::baseUrl() . '/u/' . $user['nickname'];
375 // Validate and add profile links
376 foreach ($profiles as $key => $profile) {
377 // Check for invalid profile urls (without scheme, host or path) and remove them
378 if (empty(parse_url($profile, PHP_URL_SCHEME)) || empty(parse_url($profile, PHP_URL_HOST)) || empty(parse_url($profile, PHP_URL_PATH))) {
379 unset($profiles[$key]);
383 // Add the normalized form
384 $profile = Strings::normaliseLink($profile);
385 $profiles[] = $profile;
388 $profile = str_replace('http://', 'https://', $profile);
389 $profiles[] = $profile;
392 return array_unique($profiles);
396 * Check for a "shared" notification for every new post of contacts from the given user
399 * @param int $uid User ID
400 * @return bool A contact had shared something
403 private static function checkShared(array $item, int $uid): bool
405 // Only check on original posts and reshare ("announce") activities, otherwise return
406 if (($item['gravity'] != GRAVITY_PARENT) && ($item['verb'] != Activity::ANNOUNCE)) {
410 // Check if the contact posted or shared something directly
411 if (DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true])) {
419 * Check for an implicit mention (only in tags, not in body) of the given user
422 * @param array $profiles Profile links
423 * @return bool The user is mentioned
426 private static function checkImplicitMention(array $item, array $profiles): bool
428 $mentions = Tag::getByURIId($item['uri-id'], [Tag::IMPLICIT_MENTION]);
429 foreach ($mentions as $mention) {
430 foreach ($profiles as $profile) {
431 if (Strings::compareLink($profile, $mention['url'])) {
441 * Check for an explicit mention (tag and body) of the given user
444 * @param array $profiles Profile links
445 * @return bool The user is mentioned
448 private static function checkExplicitMention(array $item, array $profiles): bool
450 $mentions = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
451 foreach ($mentions as $mention) {
452 foreach ($profiles as $profile) {
453 if (Strings::compareLink($profile, $mention['url'])) {
463 * Check if the given user had created this thread
466 * @param array $contacts Array of contact IDs
467 * @return bool The user had created this thread
470 private static function checkCommentedThread(array $item, array $contacts): bool
472 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_PARENT];
473 return Post::exists($condition);
477 * Check for a direct comment to a post of the given user
480 * @param array $contacts Array of contact IDs
481 * @return bool The item is a direct comment to a user comment
484 private static function checkDirectComment(array $item, array $contacts): bool
486 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_COMMENT];
487 return Post::exists($condition);
491 * Check for a direct comment to the starting post of the given user
494 * @param array $contacts Array of contact IDs
495 * @return bool The user had created this thread
498 private static function checkDirectCommentedThread(array $item, array $contacts): bool
500 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_PARENT];
501 return Post::exists($condition);
505 * Check if the user had commented in this thread
508 * @param array $contacts Array of contact IDs
509 * @return bool The user had commented in the thread
512 private static function checkCommentedParticipation(array $item, array $contacts): bool
514 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_COMMENT];
515 return Post::exists($condition);
519 * Check if the user had interacted in this thread (Like, Dislike, ...)
522 * @param array $contacts Array of contact IDs
523 * @return bool The user had interacted in the thread
526 private static function checkActivityParticipation(array $item, array $contacts): bool
528 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY];
529 return Post::exists($condition);