]> git.mxchange.org Git - friendica.git/blob - src/Model/Post/UserNotification.php
2a42b36340a875952e6c69c231495aa13fdd0b67
[friendica.git] / src / Model / Post / UserNotification.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Model\Post;
23
24 use BadMethodCallException;
25 use Exception;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Database\Database;
29 use Friendica\Database\DBA;
30 use Friendica\DI;
31 use Friendica\Model\Contact;
32 use Friendica\Model\Item;
33 use Friendica\Model\Post;
34 use Friendica\Model\Subscription;
35 use Friendica\Model\Tag;
36 use Friendica\Model\User;
37 use Friendica\Network\HTTPException;
38 use Friendica\Protocol\Activity;
39 use Friendica\Util\Strings;
40
41 class UserNotification
42 {
43         // Notification types
44         const TYPE_NONE                   = 0;
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;
53         const TYPE_FOLLOW                 = 256;
54         const TYPE_QUOTED                 = 512;
55
56         /**
57          * Insert a new user notification entry
58          *
59          * @param integer $uri_id
60          * @param integer $uid
61          * @param array   $data
62          * @return bool   success
63          * @throws Exception
64          */
65         public static function insert(int $uri_id, int $uid, array $data = []): bool
66         {
67                 if (empty($uri_id)) {
68                         throw new BadMethodCallException('Empty URI_id');
69                 }
70
71                 $fields = DI::dbaDefinition()->truncateFieldsForTable('post-user-notification', $data);
72
73                 $fields['uri-id'] = $uri_id;
74                 $fields['uid']    = $uid;
75
76                 return DBA::insert('post-user-notification', $fields, Database::INSERT_IGNORE);
77         }
78
79         /**
80          * Update a user notification entry
81          *
82          * @param integer $uri_id
83          * @param integer $uid
84          * @param array   $data
85          * @param bool    $insert_if_missing
86          * @return bool
87          * @throws Exception
88          */
89         public static function update(int $uri_id, int $uid, array $data = [], bool $insert_if_missing = false): bool
90         {
91                 if (empty($uri_id)) {
92                         throw new BadMethodCallException('Empty URI_id');
93                 }
94
95                 $fields = DI::dbaDefinition()->truncateFieldsForTable('post-user-notification', $data);
96
97                 // Remove the key fields
98                 unset($fields['uri-id']);
99                 unset($fields['uid']);
100
101                 if (empty($fields)) {
102                         return true;
103                 }
104
105                 return DBA::update('post-user-notification', $fields, ['uri-id' => $uri_id, 'uid' => $uid], $insert_if_missing ? true : []);
106         }
107
108         /**
109          * Delete a row from the post-user-notification table
110          *
111          * @param array $conditions  Field condition(s)
112          * @param array $options     - cascade: If true we delete records in other tables that depend on the one we're deleting through
113          *                           relations (default: true)
114          *
115          * @return boolean was the deletion successful?
116          * @throws Exception
117          */
118         public static function delete(array $conditions, array $options = []): bool
119         {
120                 return DBA::delete('post-user-notification', $conditions, $options);
121         }
122
123         /**
124          * Checks an item for notifications and sets the "notification-type" field
125          *
126          * @ToDo:
127          * - Check for mentions in posts with "uid=0" where the user hadn't interacted before
128          *
129          * @param int $uri_id URI ID
130          * @param int $uid    user ID
131          * @throws Exception
132          */
133         public static function setNotification(int $uri_id, int $uid)
134         {
135                 $fields = ['id', 'uri-id', 'parent-uri-id', 'uid', 'body', 'parent', 'gravity', 'vid', 'gravity',
136                         'contact-id', 'author-id', 'owner-id', 'causer-id', 
137                         'private', 'thr-parent', 'thr-parent-id', 'parent-uri-id', 'parent-uri', 'verb'];
138                 $item   = Post::selectFirst($fields, ['uri-id' => $uri_id, 'uid' => $uid, 'origin' => false]);
139                 if (!DBA::isResult($item)) {
140                         return;
141                 }
142
143                 // "Activity::FOLLOW" is an automated activity, so we ignore it here
144                 if ($item['verb'] == Activity::FOLLOW) {
145                         return;
146                 }
147
148                 if ($item['uid'] == 0) {
149                         $uids = [];
150                 } else {
151                         // Always include the item user
152                         $uids = [$item['uid']];
153                 }
154
155                 // Add every user who participated so far in this thread
156                 // This can only happen with participations on global items. (means: uid = 0)
157                 $users = DBA::p("SELECT DISTINCT(`contact-uid`) AS `uid` FROM `post-user-view`
158                         WHERE `contact-uid` != 0 AND `parent-uri-id` = ? AND `uid` = ?", $item['parent-uri-id'], $uid);
159                 while ($user = DBA::fetch($users)) {
160                         $uids[] = $user['uid'];
161                 }
162                 DBA::close($users);
163
164                 foreach (array_unique($uids) as $uid) {
165                         self::setNotificationForUser($item, $uid);
166                 }
167         }
168
169         /**
170          * Checks an item for notifications for the given user and sets the "notification-type" field
171          *
172          * @param array $item Item array
173          * @param int   $uid  User ID
174          * @throws HTTPException\InternalServerErrorException
175          */
176         private static function setNotificationForUser(array $item, int $uid)
177         {
178                 if (Contact\User::isBlocked($item['author-id'], $uid) || Contact\User::isIgnored($item['author-id'], $uid) || Contact\User::isCollapsed($item['author-id'], $uid)) {
179                         return;
180                 }
181
182                 if (Contact\User::isBlocked($item['owner-id'], $uid) || Contact\User::isIgnored($item['owner-id'], $uid) || Contact\User::isCollapsed($item['owner-id'], $uid)) {
183                         return;
184                 }
185
186                 if (!empty($item['causer-id']) && (Contact\User::isBlocked($item['causer-id'], $uid) || Contact\User::isIgnored($item['causer-id'], $uid) || Contact\User::isCollapsed($item['causer-id'], $uid))) {
187                         return;
188                 }
189
190                 if (Post\ThreadUser::getIgnored($item['parent-uri-id'], $uid)) {
191                         return;
192                 }
193
194                 $user = User::getById($uid, ['account-type', 'account_removed', 'account_expired']);
195                 if (in_array($user['account-type'], [User::ACCOUNT_TYPE_COMMUNITY, User::ACCOUNT_TYPE_RELAY])) {
196                         return;
197                 }
198
199                 if ($user['account_removed'] || $user['account_expired']) {
200                         return;
201                 }
202
203                 $author = Contact::getById($item['author-id'], ['contact-type']);
204                 if (empty($author)) {
205                         return;
206                 }
207
208                 $notification_type = self::TYPE_NONE;
209
210                 if (self::checkShared($item, $uid)) {
211                         $notification_type = $notification_type | self::TYPE_SHARED;
212                         self::insertNotificationByItem(self::TYPE_SHARED, $uid, $item);
213                         $notified = true;
214                 } elseif ($author['contact-type'] == Contact::TYPE_COMMUNITY) {
215                         return;
216                 } else {
217                         $notified = false;
218                 }
219
220                 $profiles = self::getProfileForUser($uid);
221
222                 // Fetch all contacts for the given profiles
223                 $contacts    = [];
224                 $iscommunity = false;
225
226                 $ret = DBA::select('contact', ['id', 'contact-type'], ['uid' => 0, 'nurl' => $profiles]);
227                 while ($contact = DBA::fetch($ret)) {
228                         $contacts[] = $contact['id'];
229
230                         if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
231                                 $iscommunity = true;
232                         }
233                 }
234                 DBA::close($ret);
235
236                 // Don't create notifications for user's posts
237                 if (in_array($item['author-id'], $contacts)) {
238                         return;
239                 }
240
241                 if (($item['verb'] != Activity::ANNOUNCE) && self::checkExplicitMention($item, $profiles)) {
242                         $notification_type = $notification_type | self::TYPE_EXPLICIT_TAGGED;
243                         if (!$notified) {
244                                 self::insertNotificationByItem(self::TYPE_EXPLICIT_TAGGED, $uid, $item);
245                                 $notified = true;
246                         }
247                 }
248
249                 if (($item['verb'] != Activity::ANNOUNCE) && self::checkImplicitMention($item, $profiles)) {
250                         $notification_type = $notification_type | self::TYPE_IMPLICIT_TAGGED;
251                         if (!$notified) {
252                                 self::insertNotificationByItem(self::TYPE_IMPLICIT_TAGGED, $uid, $item);
253                                 $notified = true;
254                         }
255                 }
256
257                 if (self::checkDirectComment($item, $contacts)) {
258                         $notification_type = $notification_type | self::TYPE_DIRECT_COMMENT;
259                         if (!$notified) {
260                                 self::insertNotificationByItem(self::TYPE_DIRECT_COMMENT, $uid, $item);
261                                 $notified = true;
262                         }
263                 }
264
265                 if (!$iscommunity && self::checkDirectCommentedThread($item, $contacts)) {
266                         $notification_type = $notification_type | self::TYPE_DIRECT_THREAD_COMMENT;
267                         if (!$notified) {
268                                 self::insertNotificationByItem(self::TYPE_DIRECT_THREAD_COMMENT, $uid, $item);
269                                 $notified = true;
270                         }
271                 }
272
273                 if (($item['verb'] != Activity::ANNOUNCE) && self::checkCommentedThread($item, $contacts)) {
274                         $notification_type = $notification_type | self::TYPE_THREAD_COMMENT;
275                         if (!$notified) {
276                                 self::insertNotificationByItem(self::TYPE_THREAD_COMMENT, $uid, $item);
277                                 $notified = true;
278                         }
279                 }
280
281                 if (($item['verb'] != Activity::ANNOUNCE) && self::checkCommentedParticipation($item, $contacts)) {
282                         $notification_type = $notification_type | self::TYPE_COMMENT_PARTICIPATION;
283                         if (!$notified) {
284                                 self::insertNotificationByItem(self::TYPE_COMMENT_PARTICIPATION, $uid, $item);
285                                 $notified = true;
286                         }
287                 }
288
289                 if (($item['verb'] != Activity::ANNOUNCE) && self::checkQuoted($item, $contacts)) {
290                         $notification_type = $notification_type | self::TYPE_QUOTED;
291                         if (!$notified) {
292                                 self::insertNotificationByItem(self::TYPE_QUOTED, $uid, $item);
293                                 $notified = true;
294                         }
295                 }
296
297                 if (($item['verb'] != Activity::ANNOUNCE) && self::checkFollowParticipation($item, $contacts)) {
298                         $notification_type = $notification_type | self::TYPE_FOLLOW;
299                         if (!$notified) {
300                                 self::insertNotificationByItem(self::TYPE_FOLLOW, $uid, $item);
301                                 $notified = true;
302                         }
303                 }
304
305                 if (($item['verb'] != Activity::ANNOUNCE) && self::checkActivityParticipation($item, $contacts)) {
306                         $notification_type = $notification_type | self::TYPE_ACTIVITY_PARTICIPATION;
307                         if (!$notified) {
308                                 self::insertNotificationByItem(self::TYPE_ACTIVITY_PARTICIPATION, $uid, $item);
309                         }
310                 }
311
312                 if (empty($notification_type)) {
313                         return;
314                 }
315
316                 // Only create notifications for posts and comments, not for activities
317                 if (($item['gravity'] == Item::GRAVITY_ACTIVITY) && ($item['verb'] != Activity::ANNOUNCE)) {
318                         return;
319                 }
320
321                 Logger::info('Set notification', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'notification-type' => $notification_type]);
322
323                 $fields = ['notification-type' => $notification_type];
324                 Post\User::update($item['uri-id'], $uid, $fields);
325                 self::update($item['uri-id'], $uid, $fields, true);
326         }
327
328         /**
329          * Add a notification entry for a given item array
330          *
331          * @param int   $type User notification type
332          * @param int   $uid  User ID
333          * @param array $item Item array
334          * @return void
335          * @throws Exception
336          */
337         private static function insertNotificationByItem(int $type, int $uid, array $item): void
338         {
339                 if (($item['verb'] != Activity::ANNOUNCE) && ($item['gravity'] == Item::GRAVITY_ACTIVITY) &&
340                         !in_array($type, [self::TYPE_DIRECT_COMMENT, self::TYPE_DIRECT_THREAD_COMMENT])) {
341                         // Activities are only stored when performed on the user's post or comment
342                         return;
343                 }
344
345                 $notification = DI::notificationFactory()->createForUser(
346                         $uid,
347                         $item['vid'],
348                         $type,
349                         $item['author-id'],
350                         $item['gravity'] == Item::GRAVITY_ACTIVITY ? $item['thr-parent-id'] : $item['uri-id'],
351                         $item['parent-uri-id']
352                 );
353
354                 try {
355                         $notification = DI::notification()->save($notification);
356                         Subscription::pushByNotification($notification);
357                 } catch (Exception $e) {
358
359                 }
360         }
361
362         /**
363          * Add a notification entry
364          *
365          * @param int    $actor Public contact ID of the actor
366          * @param string $verb  One of the Activity verb constant values
367          * @param int    $uid   User ID
368          * @return boolean
369          * @throws Exception
370          */
371         public static function insertNotification(int $actor, string $verb, int $uid): bool
372         {
373                 $notification = DI::notificationFactory()->createForRelationship(
374                         $uid,
375                         $actor,
376                         $verb
377                 );
378                 try {
379                         $notification = DI::notification()->save($notification);
380                         Subscription::pushByNotification($notification);
381                         return true;
382                 } catch (Exception $e) {
383                         return false;
384                 }
385         }
386
387         /**
388          * Fetch all profiles (contact URL) of a given user
389          *
390          * @param int $uid User ID
391          *
392          * @return array Profile links
393          * @throws HTTPException\InternalServerErrorException
394          */
395         private static function getProfileForUser(int $uid): array
396         {
397                 $notification_data = ['uid' => $uid, 'profiles' => []];
398                 Hook::callAll('check_item_notification', $notification_data);
399
400                 $profiles = $notification_data['profiles'];
401
402                 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
403                 if (!DBA::isResult($user)) {
404                         return [];
405                 }
406
407                 $owner = DBA::selectFirst('contact', ['url', 'alias'], ['self' => true, 'uid' => $uid]);
408                 if (!DBA::isResult($owner)) {
409                         return [];
410                 }
411
412                 // This is our regular URL format
413                 $profiles[] = $owner['url'];
414
415                 // Now the alias
416                 $profiles[] = $owner['alias'];
417
418                 // Notifications from Diaspora often have a URL in the Diaspora format
419                 $profiles[] = DI::baseUrl() . '/u/' . $user['nickname'];
420
421                 // Validate and add profile links
422                 foreach ($profiles as $key => $profile) {
423                         // Check for invalid profile urls (without scheme, host or path) and remove them
424                         if (empty(parse_url($profile, PHP_URL_SCHEME)) || empty(parse_url($profile, PHP_URL_HOST)) || empty(parse_url($profile, PHP_URL_PATH))) {
425                                 unset($profiles[$key]);
426                                 continue;
427                         }
428
429                         // Add the normalized form
430                         $profile    = Strings::normaliseLink($profile);
431                         $profiles[] = $profile;
432
433                         // Add the SSL form
434                         $profile    = str_replace('http://', 'https://', $profile);
435                         $profiles[] = $profile;
436                 }
437
438                 return array_unique($profiles);
439         }
440
441         /**
442          * Check for a "shared" notification for every new post of contacts from the given user
443          *
444          * @param array $item
445          * @param int   $uid User ID
446          * @return bool A contact had shared something
447          * @throws Exception
448          */
449         private static function checkShared(array $item, int $uid): bool
450         {
451                 // Only check on original posts and reshare ("announce") activities, otherwise return
452                 if (($item['gravity'] != Item::GRAVITY_PARENT) && ($item['verb'] != Activity::ANNOUNCE)) {
453                         return false;
454                 }
455
456                 // Don't notify about reshares by communities of our own posts or each time someone comments
457                 if (($item['verb'] == Activity::ANNOUNCE) && DBA::exists('contact', ['id' => $item['contact-id'], 'contact-type' => Contact::TYPE_COMMUNITY])) {
458                         $post = Post::selectFirst(['origin', 'gravity'], ['uri-id' => $item['thr-parent-id'], 'uid' => $uid]);
459                         if (!$post || $post['origin'] || ($post['gravity'] != Item::GRAVITY_PARENT)) {
460                                 return false;
461                         }
462                 }
463
464                 // Only check on posts by the user itself
465                 $cdata = Contact::getPublicAndUserContactID($item['contact-id'], $item['uid']);
466                 if (empty($cdata['user']) || ($item['author-id'] != $cdata['public'])) {
467                         return false;
468                 }
469
470                 // Check if the contact posted or shared something directly
471                 if (DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true])) {
472                         return true;
473                 }
474
475                 return false;
476         }
477
478         /**
479          * Check for an implicit mention (only in tags, not in body) of the given user
480          *
481          * @param array $item
482          * @param array $profiles Profile links
483          * @return bool The user is mentioned
484          * @throws Exception
485          */
486         private static function checkImplicitMention(array $item, array $profiles): bool
487         {
488                 $mentions = Tag::getByURIId($item['uri-id'], [Tag::IMPLICIT_MENTION]);
489                 foreach ($mentions as $mention) {
490                         foreach ($profiles as $profile) {
491                                 if (Strings::compareLink($profile, $mention['url'])) {
492                                         return true;
493                                 }
494                         }
495                 }
496
497                 return false;
498         }
499
500         /**
501          * Check for an explicit mention (tag and body) of the given user
502          *
503          * @param array $item
504          * @param array $profiles Profile links
505          * @return bool The user is mentioned
506          * @throws Exception
507          */
508         private static function checkExplicitMention(array $item, array $profiles): bool
509         {
510                 $mentions = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
511                 foreach ($mentions as $mention) {
512                         foreach ($profiles as $profile) {
513                                 if (Strings::compareLink($profile, $mention['url'])) {
514                                         return true;
515                                 }
516                         }
517                 }
518
519                 return false;
520         }
521
522         /**
523          * Check if the given user had created this thread
524          *
525          * @param array $item
526          * @param array $contacts Array of contact IDs
527          * @return bool The user had created this thread
528          * @throws Exception
529          */
530         private static function checkCommentedThread(array $item, array $contacts): bool
531         {
532                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_PARENT];
533                 return Post::exists($condition);
534         }
535
536         /**
537          * Check for a direct comment to a post of the given user
538          *
539          * @param array $item
540          * @param array $contacts Array of contact IDs
541          * @return bool The item is a direct comment to a user comment
542          * @throws Exception
543          */
544         private static function checkDirectComment(array $item, array $contacts): bool
545         {
546                 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_COMMENT];
547                 return Post::exists($condition);
548         }
549
550         /**
551          * Check for a direct comment to the starting post of the given user
552          *
553          * @param array $item
554          * @param array $contacts Array of contact IDs
555          * @return bool The user had created this thread
556          * @throws Exception
557          */
558         private static function checkDirectCommentedThread(array $item, array $contacts): bool
559         {
560                 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_PARENT];
561                 return Post::exists($condition);
562         }
563
564         /**
565          *  Check if the user had commented in this thread
566          *
567          * @param array $item
568          * @param array $contacts Array of contact IDs
569          * @return bool The user had commented in the thread
570          * @throws Exception
571          */
572         private static function checkCommentedParticipation(array $item, array $contacts): bool
573         {
574                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_COMMENT];
575                 return Post::exists($condition);
576         }
577
578         /**
579          * Check if the user follows this thread
580          *
581          * @param array $item
582          * @param array $contacts Array of contact IDs
583          * @return bool The user follows the thread
584          * @throws Exception
585          */
586         private static function checkFollowParticipation(array $item, array $contacts): bool
587         {
588                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_ACTIVITY, 'verb' => Activity::FOLLOW];
589                 return Post::exists($condition);
590         }
591
592         /**
593          * Check if the user had interacted in this thread (Like, Dislike, ...)
594          *
595          * @param array $item
596          * @param array $contacts Array of contact IDs
597          * @return bool The user had interacted in the thread
598          * @throws Exception
599          */
600         private static function checkActivityParticipation(array $item, array $contacts): bool
601         {
602                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_ACTIVITY];
603                 return Post::exists($condition);
604         }
605
606         /**
607          * Check for a quoted post of a post of the given user
608          *
609          * @param array $item
610          * @param array $contacts Array of contact IDs
611          * @return bool The item is a quoted post of a user's post or comment
612          * @throws Exception
613          */
614         private static function checkQuoted(array $item, array $contacts): bool
615         {
616                 if (empty($item['quote-uri-id'])) {
617                         return false;
618                 }
619                 $condition = ['uri-id' => $item['quote-uri-id'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => [item::GRAVITY_PARENT, Item::GRAVITY_COMMENT]];
620                 return Post::exists($condition);
621         }
622
623
624 }