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\Model\Subscription;
34 use Friendica\Util\Strings;
35 use Friendica\Model\Tag;
36 use Friendica\Protocol\Activity;
37 use Friendica\Util\DateTimeFormat;
39 class UserNotification
43 const NOTIF_EXPLICIT_TAGGED = 1;
44 const NOTIF_IMPLICIT_TAGGED = 2;
45 const NOTIF_THREAD_COMMENT = 4;
46 const NOTIF_DIRECT_COMMENT = 8;
47 const NOTIF_COMMENT_PARTICIPATION = 16;
48 const NOTIF_ACTIVITY_PARTICIPATION = 32;
49 const NOTIF_DIRECT_THREAD_COMMENT = 64;
50 const NOTIF_SHARED = 128;
54 * Insert a new user notification entry
56 * @param integer $uri_id
58 * @param array $fields
59 * @return bool success
62 public static function insert(int $uri_id, int $uid, array $data = [])
65 throw new BadMethodCallException('Empty URI_id');
68 $fields = DBStructure::getFieldsForTable('post-user-notification', $data);
70 // Additionally assign the key fields
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)
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
111 * - 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 delete successful?
117 public static function delete(array $conditions, array $options = [])
119 return DBA::delete('post-user-notification', $conditions, $options);
123 * 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
130 public static function setNotification(int $uri_id, int $uid)
132 $fields = ['id', 'uri-id', 'parent-uri-id', 'uid', 'body', 'parent', 'gravity', 'vid', 'gravity',
133 'private', 'contact-id', 'thr-parent', 'thr-parent-id', 'parent-uri-id', 'parent-uri', 'author-id', 'verb'];
134 $item = Post::selectFirst($fields, ['uri-id' => $uri_id, 'uid' => $uid, 'origin' => false]);
135 if (!DBA::isResult($item)) {
139 // "Activity::FOLLOW" is an automated activity, so we ignore it here
140 if ($item['verb'] == Activity::FOLLOW) {
144 if ($item['uid'] == 0) {
147 // Always include the item user
148 $uids = [$item['uid']];
151 // Add every user who participated so far in this thread
152 // This can only happen with participations on global items. (means: uid = 0)
153 $users = DBA::p("SELECT DISTINCT(`contact-uid`) AS `uid` FROM `post-user-view`
154 WHERE `contact-uid` != 0 AND `parent-uri-id` = ? AND `uid` = ?", $item['parent-uri-id'], $uid);
155 while ($user = DBA::fetch($users)) {
156 $uids[] = $user['uid'];
160 foreach (array_unique($uids) as $uid) {
161 self::setNotificationForUser($item, $uid);
166 * Checks an item for notifications for the given user and sets the "notification-type" field
168 * @param array $item Item array
169 * @param int $uid User ID
171 private static function setNotificationForUser(array $item, int $uid)
173 if (Post\ThreadUser::getIgnored($item['parent-uri-id'], $uid)) {
177 $notification_type = self::NOTIF_NONE;
179 if (self::checkShared($item, $uid)) {
180 $notification_type = $notification_type | self::NOTIF_SHARED;
181 self::insertNoticationByItem(self::NOTIF_SHARED, $uid, $item);
187 $profiles = self::getProfileForUser($uid);
189 // Fetch all contacts for the given profiles
191 $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
192 while ($contact = DBA::fetch($ret)) {
193 $contacts[] = $contact['id'];
197 // Don't create notifications for user's posts
198 if (in_array($item['author-id'], $contacts)) {
202 if (self::checkExplicitMention($item, $profiles)) {
203 $notification_type = $notification_type | self::NOTIF_EXPLICIT_TAGGED;
205 self::insertNoticationByItem( self::NOTIF_EXPLICIT_TAGGED, $uid, $item);
210 if (self::checkImplicitMention($item, $profiles)) {
211 $notification_type = $notification_type | self::NOTIF_IMPLICIT_TAGGED;
213 self::insertNoticationByItem(self::NOTIF_IMPLICIT_TAGGED, $uid, $item);
218 if (self::checkDirectComment($item, $contacts)) {
219 $notification_type = $notification_type | self::NOTIF_DIRECT_COMMENT;
221 self::insertNoticationByItem(self::NOTIF_DIRECT_COMMENT, $uid, $item);
226 if (self::checkDirectCommentedThread($item, $contacts)) {
227 $notification_type = $notification_type | self::NOTIF_DIRECT_THREAD_COMMENT;
229 self::insertNoticationByItem(self::NOTIF_DIRECT_THREAD_COMMENT, $uid, $item);
234 if (self::checkCommentedThread($item, $contacts)) {
235 $notification_type = $notification_type | self::NOTIF_THREAD_COMMENT;
237 self::insertNoticationByItem(self::NOTIF_THREAD_COMMENT, $uid, $item);
242 if (self::checkCommentedParticipation($item, $contacts)) {
243 $notification_type = $notification_type | self::NOTIF_COMMENT_PARTICIPATION;
245 self::insertNoticationByItem(self::NOTIF_COMMENT_PARTICIPATION, $uid, $item);
250 if (self::checkActivityParticipation($item, $contacts)) {
251 $notification_type = $notification_type | self::NOTIF_ACTIVITY_PARTICIPATION;
253 self::insertNoticationByItem(self::NOTIF_ACTIVITY_PARTICIPATION, $uid, $item);
258 // Only create notifications for posts and comments, not for activities
259 if (empty($notification_type) || !in_array($item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT])) {
263 Logger::info('Set notification', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'notification-type' => $notification_type]);
265 $fields = ['notification-type' => $notification_type];
266 Post\User::update($item['uri-id'], $uid, $fields);
267 self::update($item['uri-id'], $uid, $fields, true);
271 * Add a notification entry for a given item array
273 * @param int $type User notification type
274 * @param int $uid User ID
275 * @param array $item Item array
278 private static function insertNoticationByItem(int $type, int $uid, array $item)
280 if (($item['gravity'] == GRAVITY_ACTIVITY) &&
281 !in_array($type, [self::NOTIF_DIRECT_COMMENT, self::NOTIF_DIRECT_THREAD_COMMENT])) {
282 // Activities are only stored when performed on the user's post or comment
288 'vid' => $item['vid'],
290 'actor-id' => $item['author-id'],
291 'parent-uri-id' => $item['parent-uri-id'],
292 'created' => DateTimeFormat::utcNow(),
295 if ($item['gravity'] == GRAVITY_ACTIVITY) {
296 $fields['target-uri-id'] = $item['thr-parent-id'];
298 $fields['target-uri-id'] = $item['uri-id'];
301 $ret = DBA::insert('notification', $fields, Database::INSERT_IGNORE);
303 $id = DBA::lastInsertId();
305 Subscription::pushByNotificationId($id);
312 * Add a notification entry
314 * @param int $actor Contact ID of the actor
315 * @param int $vid Verb ID
316 * @param int $uid User ID
319 public static function insertNotication(int $actor, int $vid, int $uid)
324 'type' => self::NOTIF_NONE,
325 'actor-id' => $actor,
326 'created' => DateTimeFormat::utcNow(),
329 $ret = DBA::insert('notification', $fields, Database::INSERT_IGNORE);
331 $id = DBA::lastInsertId();
333 Subscription::pushByNotificationId($id);
340 * Fetch all profiles (contact URL) of a given user
341 * @param int $uid User ID
343 * @return array Profile links
345 private static function getProfileForUser(int $uid)
347 $notification_data = ['uid' => $uid, 'profiles' => []];
348 Hook::callAll('check_item_notification', $notification_data);
350 $profiles = $notification_data['profiles'];
352 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
353 if (!DBA::isResult($user)) {
357 $owner = DBA::selectFirst('contact', ['url', 'alias'], ['self' => true, 'uid' => $uid]);
358 if (!DBA::isResult($owner)) {
362 // This is our regular URL format
363 $profiles[] = $owner['url'];
366 $profiles[] = $owner['alias'];
368 // Notifications from Diaspora are often with an URL in the Diaspora format
369 $profiles[] = DI::baseUrl() . '/u/' . $user['nickname'];
371 // Validate and add profile links
372 foreach ($profiles AS $key => $profile) {
373 // Check for invalid profile urls (without scheme, host or path) and remove them
374 if (empty(parse_url($profile, PHP_URL_SCHEME)) || empty(parse_url($profile, PHP_URL_HOST)) || empty(parse_url($profile, PHP_URL_PATH))) {
375 unset($profiles[$key]);
379 // Add the normalized form
380 $profile = Strings::normaliseLink($profile);
381 $profiles[] = $profile;
384 $profile = str_replace('http://', 'https://', $profile);
385 $profiles[] = $profile;
388 return array_unique($profiles);
392 * Check for a "shared" notification for every new post of contacts from the given user
394 * @param int $uid User ID
395 * @return bool A contact had shared something
397 private static function checkShared(array $item, int $uid)
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])) {
409 // The following check doesn't make sense on activities, so quit here
410 if ($item['verb'] == Activity::ANNOUNCE) {
414 // Check if the contact is a mentioned forum
415 $tags = DBA::select('tag-view', ['url'], ['uri-id' => $item['uri-id'], 'type' => [Tag::MENTION, Tag::EXCLUSIVE_MENTION]]);
416 while ($tag = DBA::fetch($tags)) {
417 $condition = ['nurl' => Strings::normaliseLink($tag['url']), 'uid' => $uid, 'notify_new_posts' => true, 'contact-type' => Contact::TYPE_COMMUNITY];
418 if (DBA::exists('contact', $condition)) {
428 * Check for an implicit mention (only tag, no body) of the given user
430 * @param array $profiles Profile links
431 * @return bool The user is mentioned
433 private static function checkImplicitMention(array $item, array $profiles)
435 $mentions = Tag::getByURIId($item['uri-id'], [Tag::IMPLICIT_MENTION]);
436 foreach ($mentions as $mention) {
437 foreach ($profiles as $profile) {
438 if (Strings::compareLink($profile, $mention['url'])) {
448 * Check for an explicit mention (tag and body) of the given user
450 * @param array $profiles Profile links
451 * @return bool The user is mentioned
453 private static function checkExplicitMention(array $item, array $profiles)
455 $mentions = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
456 foreach ($mentions as $mention) {
457 foreach ($profiles as $profile) {
458 if (Strings::compareLink($profile, $mention['url'])) {
468 * Check if the given user had created this thread
470 * @param array $contacts Array of contact IDs
471 * @return bool The user had created this thread
473 private static function checkCommentedThread(array $item, array $contacts)
475 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_PARENT];
476 return Post::exists($condition);
480 * Check for a direct comment to a post of the given user
482 * @param array $contacts Array of contact IDs
483 * @return bool The item is a direct comment to a user comment
485 private static function checkDirectComment(array $item, array $contacts)
487 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_COMMENT];
488 return Post::exists($condition);
492 * 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
497 private static function checkDirectCommentedThread(array $item, array $contacts)
499 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_PARENT];
500 return Post::exists($condition);
504 * Check if the user had commented in this thread
506 * @param array $contacts Array of contact IDs
507 * @return bool The user had commented in the thread
509 private static function checkCommentedParticipation(array $item, array $contacts)
511 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_COMMENT];
512 return Post::exists($condition);
516 * Check if the user had interacted in this thread (Like, Dislike, ...)
518 * @param array $contacts Array of contact IDs
519 * @return bool The user had interacted in the thread
521 private static function checkActivityParticipation(array $item, array $contacts)
523 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY];
524 return Post::exists($condition);