3 * @copyright Copyright (C) 2010-2021, 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;
25 use Friendica\Core\Logger;
26 use Friendica\Core\Hook;
27 use Friendica\Database\Database;
28 use Friendica\Database\DBA;
29 use Friendica\Database\DBStructure;
31 use Friendica\Model\Contact;
32 use Friendica\Model\Post;
33 use Friendica\Util\Strings;
34 use Friendica\Model\Tag;
35 use Friendica\Protocol\Activity;
36 use Friendica\Util\DateTimeFormat;
38 class UserNotification
42 const NOTIF_EXPLICIT_TAGGED = 1;
43 const NOTIF_IMPLICIT_TAGGED = 2;
44 const NOTIF_THREAD_COMMENT = 4;
45 const NOTIF_DIRECT_COMMENT = 8;
46 const NOTIF_COMMENT_PARTICIPATION = 16;
47 const NOTIF_ACTIVITY_PARTICIPATION = 32;
48 const NOTIF_DIRECT_THREAD_COMMENT = 64;
49 const NOTIF_SHARED = 128;
53 * Insert a new user notification entry
55 * @param integer $uri_id
57 * @param array $fields
58 * @return bool success
61 public static function insert(int $uri_id, int $uid, array $data = [])
64 throw new BadMethodCallException('Empty URI_id');
67 $fields = DBStructure::getFieldsForTable('post-user-notification', $data);
69 // Additionally assign the key fields
70 $fields['uri-id'] = $uri_id;
71 $fields['uid'] = $uid;
73 return DBA::insert('post-user-notification', $fields, Database::INSERT_IGNORE);
77 * Update a user notification entry
79 * @param integer $uri_id
82 * @param bool $insert_if_missing
86 public static function update(int $uri_id, int $uid, array $data = [], bool $insert_if_missing = false)
89 throw new BadMethodCallException('Empty URI_id');
92 $fields = DBStructure::getFieldsForTable('post-user-notification', $data);
94 // Remove the key fields
95 unset($fields['uri-id']);
96 unset($fields['uid']);
102 return DBA::update('post-user-notification', $fields, ['uri-id' => $uri_id, 'uid' => $uid], $insert_if_missing ? true : []);
106 * Delete a row from the post-user-notification table
108 * @param array $conditions Field condition(s)
109 * @param array $options
110 * - 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 delete successful?
116 public static function delete(array $conditions, array $options = [])
118 return DBA::delete('post-user-notification', $conditions, $options);
122 * Checks an item for notifications and sets the "notification-type" field
124 * - Check for mentions in posts with "uid=0" where the user hadn't interacted before
126 * @param int $uri_id URI ID
127 * @param int $uid user ID
129 public static function setNotification(int $uri_id, int $uid)
131 $fields = ['id', 'uri-id', 'parent-uri-id', 'uid', 'body', 'parent', 'gravity', 'vid', 'gravity',
132 'private', 'contact-id', 'thr-parent', 'thr-parent-id', 'parent-uri-id', 'parent-uri', 'author-id', 'verb'];
133 $item = Post::selectFirst($fields, ['uri-id' => $uri_id, 'uid' => $uid, 'origin' => false]);
134 if (!DBA::isResult($item)) {
138 // "Activity::FOLLOW" is an automated activity, so we ignore it here
139 if ($item['verb'] == Activity::FOLLOW) {
143 if ($item['uid'] == 0) {
146 // Always include the item user
147 $uids = [$item['uid']];
150 // Add every user who participated so far in this thread
151 // This can only happen with participations on global items. (means: uid = 0)
152 $users = DBA::p("SELECT DISTINCT(`contact-uid`) AS `uid` FROM `post-user-view`
153 WHERE `contact-uid` != 0 AND `parent-uri-id` = ? AND `uid` = ?", $item['parent-uri-id'], $uid);
154 while ($user = DBA::fetch($users)) {
155 $uids[] = $user['uid'];
159 foreach (array_unique($uids) as $uid) {
160 self::setNotificationForUser($item, $uid);
165 * Checks an item for notifications for the given user and sets the "notification-type" field
167 * @param array $item Item array
168 * @param int $uid User ID
170 private static function setNotificationForUser(array $item, int $uid)
172 if (Post\ThreadUser::getIgnored($item['parent-uri-id'], $uid)) {
176 $notification_type = self::NOTIF_NONE;
178 if (self::checkShared($item, $uid)) {
179 $notification_type = $notification_type | self::NOTIF_SHARED;
180 self::insertNoticationByItem(self::NOTIF_SHARED, $uid, $item);
186 $profiles = self::getProfileForUser($uid);
188 // Fetch all contacts for the given profiles
190 $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
191 while ($contact = DBA::fetch($ret)) {
192 $contacts[] = $contact['id'];
196 // Don't create notifications for user's posts
197 if (in_array($item['author-id'], $contacts)) {
201 if (self::checkExplicitMention($item, $profiles)) {
202 $notification_type = $notification_type | self::NOTIF_EXPLICIT_TAGGED;
204 self::insertNoticationByItem( self::NOTIF_EXPLICIT_TAGGED, $uid, $item);
209 if (self::checkImplicitMention($item, $profiles)) {
210 $notification_type = $notification_type | self::NOTIF_IMPLICIT_TAGGED;
212 self::insertNoticationByItem(self::NOTIF_IMPLICIT_TAGGED, $uid, $item);
217 if (self::checkDirectComment($item, $contacts)) {
218 $notification_type = $notification_type | self::NOTIF_DIRECT_COMMENT;
220 self::insertNoticationByItem(self::NOTIF_DIRECT_COMMENT, $uid, $item);
225 if (self::checkDirectCommentedThread($item, $contacts)) {
226 $notification_type = $notification_type | self::NOTIF_DIRECT_THREAD_COMMENT;
228 self::insertNoticationByItem(self::NOTIF_DIRECT_THREAD_COMMENT, $uid, $item);
233 if (self::checkCommentedThread($item, $contacts)) {
234 $notification_type = $notification_type | self::NOTIF_THREAD_COMMENT;
236 self::insertNoticationByItem(self::NOTIF_THREAD_COMMENT, $uid, $item);
241 if (self::checkCommentedParticipation($item, $contacts)) {
242 $notification_type = $notification_type | self::NOTIF_COMMENT_PARTICIPATION;
244 self::insertNoticationByItem(self::NOTIF_COMMENT_PARTICIPATION, $uid, $item);
249 if (self::checkActivityParticipation($item, $contacts)) {
250 $notification_type = $notification_type | self::NOTIF_ACTIVITY_PARTICIPATION;
252 self::insertNoticationByItem(self::NOTIF_ACTIVITY_PARTICIPATION, $uid, $item);
257 // Only create notifications for posts and comments, not for activities
258 if (empty($notification_type) || !in_array($item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT])) {
262 Logger::info('Set notification', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'notification-type' => $notification_type]);
264 $fields = ['notification-type' => $notification_type];
265 Post\User::update($item['uri-id'], $uid, $fields);
266 self::update($item['uri-id'], $uid, $fields, true);
270 * Add a notification entry for a given item array
272 * @param int $type User notification type
273 * @param int $uid User ID
274 * @param array $item Item array
277 private static function insertNoticationByItem(int $type, int $uid, array $item)
279 if (($item['gravity'] == GRAVITY_ACTIVITY) &&
280 !in_array($type, [self::NOTIF_DIRECT_COMMENT, self::NOTIF_DIRECT_THREAD_COMMENT])) {
281 // Activities are only stored when performed on the user's post or comment
287 'vid' => $item['vid'],
289 'actor-id' => $item['author-id'],
290 'parent-uri-id' => $item['parent-uri-id'],
291 'created' => DateTimeFormat::utcNow(),
294 if ($item['gravity'] == GRAVITY_ACTIVITY) {
295 $fields['target-uri-id'] = $item['thr-parent-id'];
297 $fields['target-uri-id'] = $item['uri-id'];
300 return DBA::insert('notification', $fields, Database::INSERT_IGNORE);
304 * Add a notification entry
306 * @param int $actor Contact ID of the actor
307 * @param int $vid Verb ID
308 * @param int $uid User ID
311 public static function insertNotication(int $actor, int $vid, int $uid)
316 'type' => self::NOTIF_NONE,
317 'actor-id' => $actor,
318 'created' => DateTimeFormat::utcNow(),
321 return DBA::insert('notification', $fields, Database::INSERT_IGNORE);
325 * Fetch all profiles (contact URL) of a given user
326 * @param int $uid User ID
328 * @return array Profile links
330 private static function getProfileForUser(int $uid)
332 $notification_data = ['uid' => $uid, 'profiles' => []];
333 Hook::callAll('check_item_notification', $notification_data);
335 $profiles = $notification_data['profiles'];
337 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
338 if (!DBA::isResult($user)) {
342 $owner = DBA::selectFirst('contact', ['url', 'alias'], ['self' => true, 'uid' => $uid]);
343 if (!DBA::isResult($owner)) {
347 // This is our regular URL format
348 $profiles[] = $owner['url'];
351 $profiles[] = $owner['alias'];
353 // Notifications from Diaspora are often with an URL in the Diaspora format
354 $profiles[] = DI::baseUrl() . '/u/' . $user['nickname'];
356 // Validate and add profile links
357 foreach ($profiles AS $key => $profile) {
358 // Check for invalid profile urls (without scheme, host or path) and remove them
359 if (empty(parse_url($profile, PHP_URL_SCHEME)) || empty(parse_url($profile, PHP_URL_HOST)) || empty(parse_url($profile, PHP_URL_PATH))) {
360 unset($profiles[$key]);
364 // Add the normalized form
365 $profile = Strings::normaliseLink($profile);
366 $profiles[] = $profile;
369 $profile = str_replace('http://', 'https://', $profile);
370 $profiles[] = $profile;
373 return array_unique($profiles);
377 * Check for a "shared" notification for every new post of contacts from the given user
379 * @param int $uid User ID
380 * @return bool A contact had shared something
382 private static function checkShared(array $item, int $uid)
384 // Only check on original posts and reshare ("announce") activities, otherwise return
385 if (($item['gravity'] != GRAVITY_PARENT) && ($item['verb'] != Activity::ANNOUNCE)) {
389 // Check if the contact posted or shared something directly
390 if (DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true])) {
394 // The following check doesn't make sense on activities, so quit here
395 if ($item['verb'] == Activity::ANNOUNCE) {
399 // Check if the contact is a mentioned forum
400 $tags = DBA::select('tag-view', ['url'], ['uri-id' => $item['uri-id'], 'type' => [Tag::MENTION, Tag::EXCLUSIVE_MENTION]]);
401 while ($tag = DBA::fetch($tags)) {
402 $condition = ['nurl' => Strings::normaliseLink($tag['url']), 'uid' => $uid, 'notify_new_posts' => true, 'contact-type' => Contact::TYPE_COMMUNITY];
403 if (DBA::exists('contact', $condition)) {
413 * Check for an implicit mention (only tag, no body) of the given user
415 * @param array $profiles Profile links
416 * @return bool The user is mentioned
418 private static function checkImplicitMention(array $item, array $profiles)
420 $mentions = Tag::getByURIId($item['uri-id'], [Tag::IMPLICIT_MENTION]);
421 foreach ($mentions as $mention) {
422 foreach ($profiles as $profile) {
423 if (Strings::compareLink($profile, $mention['url'])) {
433 * Check for an explicit mention (tag and body) of the given user
435 * @param array $profiles Profile links
436 * @return bool The user is mentioned
438 private static function checkExplicitMention(array $item, array $profiles)
440 $mentions = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
441 foreach ($mentions as $mention) {
442 foreach ($profiles as $profile) {
443 if (Strings::compareLink($profile, $mention['url'])) {
453 * Check if the given user had created this thread
455 * @param array $contacts Array of contact IDs
456 * @return bool The user had created this thread
458 private static function checkCommentedThread(array $item, array $contacts)
460 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_PARENT];
461 return Post::exists($condition);
465 * Check for a direct comment to a post of the given user
467 * @param array $contacts Array of contact IDs
468 * @return bool The item is a direct comment to a user comment
470 private static function checkDirectComment(array $item, array $contacts)
472 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_COMMENT];
473 return Post::exists($condition);
477 * Check for a direct comment to the starting post of the given user
479 * @param array $contacts Array of contact IDs
480 * @return bool The user had created this thread
482 private static function checkDirectCommentedThread(array $item, array $contacts)
484 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_PARENT];
485 return Post::exists($condition);
489 * Check if the user had commented in this thread
491 * @param array $contacts Array of contact IDs
492 * @return bool The user had commented in the thread
494 private static function checkCommentedParticipation(array $item, array $contacts)
496 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_COMMENT];
497 return Post::exists($condition);
501 * Check if the user had interacted in this thread (Like, Dislike, ...)
503 * @param array $contacts Array of contact IDs
504 * @return bool The user had interacted in the thread
506 private static function checkActivityParticipation(array $item, array $contacts)
508 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY];
509 return Post::exists($condition);