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