3 * @copyright Copyright (C) 2020, Friendica
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;
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',
132 'private', 'contact-id', 'thr-parent', '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;
182 $profiles = self::getProfileForUser($uid);
184 // Fetch all contacts for the given profiles
186 $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
187 while ($contact = DBA::fetch($ret)) {
188 $contacts[] = $contact['id'];
192 // Don't create notifications for user's posts
193 if (in_array($item['author-id'], $contacts)) {
197 // Only create notifications for posts and comments, not for activities
198 if (in_array($item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT])) {
199 if (self::checkImplicitMention($item, $profiles)) {
200 $notification_type = $notification_type | self::NOTIF_IMPLICIT_TAGGED;
203 if (self::checkExplicitMention($item, $profiles)) {
204 $notification_type = $notification_type | self::NOTIF_EXPLICIT_TAGGED;
207 if (self::checkCommentedThread($item, $contacts)) {
208 $notification_type = $notification_type | self::NOTIF_THREAD_COMMENT;
211 if (self::checkDirectComment($item, $contacts)) {
212 $notification_type = $notification_type | self::NOTIF_DIRECT_COMMENT;
215 if (self::checkDirectCommentedThread($item, $contacts)) {
216 $notification_type = $notification_type | self::NOTIF_DIRECT_THREAD_COMMENT;
219 if (self::checkCommentedParticipation($item, $contacts)) {
220 $notification_type = $notification_type | self::NOTIF_COMMENT_PARTICIPATION;
223 if (self::checkActivityParticipation($item, $contacts)) {
224 $notification_type = $notification_type | self::NOTIF_ACTIVITY_PARTICIPATION;
228 if (empty($notification_type)) {
232 Logger::info('Set notification', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'notification-type' => $notification_type]);
234 $fields = ['notification-type' => $notification_type];
235 Post\User::update($item['uri-id'], $uid, $fields);
236 self::update($item['uri-id'], $uid, $fields, true);
240 * Fetch all profiles (contact URL) of a given user
241 * @param int $uid User ID
243 * @return array Profile links
245 private static function getProfileForUser(int $uid)
247 $notification_data = ['uid' => $uid, 'profiles' => []];
248 Hook::callAll('check_item_notification', $notification_data);
250 $profiles = $notification_data['profiles'];
252 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
253 if (!DBA::isResult($user)) {
257 $owner = DBA::selectFirst('contact', ['url', 'alias'], ['self' => true, 'uid' => $uid]);
258 if (!DBA::isResult($owner)) {
262 // This is our regular URL format
263 $profiles[] = $owner['url'];
266 $profiles[] = $owner['alias'];
268 // Notifications from Diaspora are often with an URL in the Diaspora format
269 $profiles[] = DI::baseUrl() . '/u/' . $user['nickname'];
271 // Validate and add profile links
272 foreach ($profiles AS $key => $profile) {
273 // Check for invalid profile urls (without scheme, host or path) and remove them
274 if (empty(parse_url($profile, PHP_URL_SCHEME)) || empty(parse_url($profile, PHP_URL_HOST)) || empty(parse_url($profile, PHP_URL_PATH))) {
275 unset($profiles[$key]);
279 // Add the normalized form
280 $profile = Strings::normaliseLink($profile);
281 $profiles[] = $profile;
284 $profile = str_replace('http://', 'https://', $profile);
285 $profiles[] = $profile;
288 return array_unique($profiles);
292 * Check for a "shared" notification for every new post of contacts from the given user
294 * @param int $uid User ID
295 * @return bool A contact had shared something
297 private static function checkShared(array $item, int $uid)
299 // Only check on original posts and reshare ("announce") activities, otherwise return
300 if (($item['gravity'] != GRAVITY_PARENT) && ($item['verb'] != Activity::ANNOUNCE)) {
304 // Check if the contact posted or shared something directly
305 if (DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true])) {
309 // The following check doesn't make sense on activities, so quit here
310 if ($item['verb'] == Activity::ANNOUNCE) {
314 // Check if the contact is a mentioned forum
315 $tags = DBA::select('tag-view', ['url'], ['uri-id' => $item['uri-id'], 'type' => [Tag::MENTION, Tag::EXCLUSIVE_MENTION]]);
316 while ($tag = DBA::fetch($tags)) {
317 $condition = ['nurl' => Strings::normaliseLink($tag['url']), 'uid' => $uid, 'notify_new_posts' => true, 'contact-type' => Contact::TYPE_COMMUNITY];
318 if (DBA::exists('contact', $condition)) {
328 * Check for an implicit mention (only tag, no body) of the given user
330 * @param array $profiles Profile links
331 * @return bool The user is mentioned
333 private static function checkImplicitMention(array $item, array $profiles)
335 $mentions = Tag::getByURIId($item['uri-id'], [Tag::IMPLICIT_MENTION]);
336 foreach ($mentions as $mention) {
337 foreach ($profiles as $profile) {
338 if (Strings::compareLink($profile, $mention['url'])) {
348 * Check for an explicit mention (tag and body) of the given user
350 * @param array $profiles Profile links
351 * @return bool The user is mentioned
353 private static function checkExplicitMention(array $item, array $profiles)
355 $mentions = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
356 foreach ($mentions as $mention) {
357 foreach ($profiles as $profile) {
358 if (Strings::compareLink($profile, $mention['url'])) {
368 * Check if the given user had created this thread
370 * @param array $contacts Array of contact IDs
371 * @return bool The user had created this thread
373 private static function checkCommentedThread(array $item, array $contacts)
375 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_PARENT];
376 return Post::exists($condition);
380 * Check for a direct comment to a post of the given user
382 * @param array $contacts Array of contact IDs
383 * @return bool The item is a direct comment to a user comment
385 private static function checkDirectComment(array $item, array $contacts)
387 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_COMMENT];
388 return Post::exists($condition);
392 * Check for a direct comment to the starting post of the given user
394 * @param array $contacts Array of contact IDs
395 * @return bool The user had created this thread
397 private static function checkDirectCommentedThread(array $item, array $contacts)
399 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_PARENT];
400 return Post::exists($condition);
404 * Check if the user had commented in this thread
406 * @param array $contacts Array of contact IDs
407 * @return bool The user had commented in the thread
409 private static function checkCommentedParticipation(array $item, array $contacts)
411 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_COMMENT];
412 return Post::exists($condition);
416 * Check if the user had interacted in this thread (Like, Dislike, ...)
418 * @param array $contacts Array of contact IDs
419 * @return bool The user had interacted in the thread
421 private static function checkActivityParticipation(array $item, array $contacts)
423 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY];
424 return Post::exists($condition);