]> git.mxchange.org Git - friendica.git/blob - src/Model/Post/UserNotification.php
Merge remote-tracking branch 'upstream/2022.12-rc' into diaspora-reshare
[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\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                            'private', 'contact-id', 'thr-parent', 'thr-parent-id', 'parent-uri-id', 'parent-uri', 'author-id', 'verb'];
137                 $item   = Post::selectFirst($fields, ['uri-id' => $uri_id, 'uid' => $uid, 'origin' => false]);
138                 if (!DBA::isResult($item)) {
139                         return;
140                 }
141
142                 // "Activity::FOLLOW" is an automated activity, so we ignore it here
143                 if ($item['verb'] == Activity::FOLLOW) {
144                         return;
145                 }
146
147                 if ($item['uid'] == 0) {
148                         $uids = [];
149                 } else {
150                         // Always include the item user
151                         $uids = [$item['uid']];
152                 }
153
154                 // Add every user who participated so far in this thread
155                 // This can only happen with participations on global items. (means: uid = 0)
156                 $users = DBA::p("SELECT DISTINCT(`contact-uid`) AS `uid` FROM `post-user-view`
157                         WHERE `contact-uid` != 0 AND `parent-uri-id` = ? AND `uid` = ?", $item['parent-uri-id'], $uid);
158                 while ($user = DBA::fetch($users)) {
159                         $uids[] = $user['uid'];
160                 }
161                 DBA::close($users);
162
163                 foreach (array_unique($uids) as $uid) {
164                         self::setNotificationForUser($item, $uid);
165                 }
166         }
167
168         /**
169          * Checks an item for notifications for the given user and sets the "notification-type" field
170          *
171          * @param array $item Item array
172          * @param int   $uid  User ID
173          * @throws HTTPException\InternalServerErrorException
174          */
175         private static function setNotificationForUser(array $item, int $uid)
176         {
177                 if (Post\ThreadUser::getIgnored($item['parent-uri-id'], $uid)) {
178                         return;
179                 }
180
181                 $user = User::getById($uid, ['account-type', 'account_removed', 'account_expired']);
182                 if (in_array($user['account-type'], [User::ACCOUNT_TYPE_COMMUNITY, User::ACCOUNT_TYPE_RELAY])) {
183                         return;
184                 }
185
186                 if ($user['account_removed'] || $user['account_expired']) {
187                         return;
188                 }
189
190                 $author = Contact::getById($item['author-id'], ['contact-type']);
191                 if (empty($author)) {
192                         return;
193                 }
194
195                 $notification_type = self::TYPE_NONE;
196
197                 if (self::checkShared($item, $uid)) {
198                         $notification_type = $notification_type | self::TYPE_SHARED;
199                         self::insertNotificationByItem(self::TYPE_SHARED, $uid, $item);
200                         $notified = true;
201                 } elseif ($author['contact-type'] == Contact::TYPE_COMMUNITY) {
202                         return;
203                 } else {
204                         $notified = false;
205                 }
206
207                 $profiles = self::getProfileForUser($uid);
208
209                 // Fetch all contacts for the given profiles
210                 $contacts    = [];
211                 $iscommunity = false;
212
213                 $ret = DBA::select('contact', ['id', 'contact-type'], ['uid' => 0, 'nurl' => $profiles]);
214                 while ($contact = DBA::fetch($ret)) {
215                         $contacts[] = $contact['id'];
216
217                         if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
218                                 $iscommunity = true;
219                         }
220                 }
221                 DBA::close($ret);
222
223                 // Don't create notifications for user's posts
224                 if (in_array($item['author-id'], $contacts)) {
225                         return;
226                 }
227
228                 if (($item['verb'] != Activity::ANNOUNCE) && self::checkExplicitMention($item, $profiles)) {
229                         $notification_type = $notification_type | self::TYPE_EXPLICIT_TAGGED;
230                         if (!$notified) {
231                                 self::insertNotificationByItem(self::TYPE_EXPLICIT_TAGGED, $uid, $item);
232                                 $notified = true;
233                         }
234                 }
235
236                 if (($item['verb'] != Activity::ANNOUNCE) && self::checkImplicitMention($item, $profiles)) {
237                         $notification_type = $notification_type | self::TYPE_IMPLICIT_TAGGED;
238                         if (!$notified) {
239                                 self::insertNotificationByItem(self::TYPE_IMPLICIT_TAGGED, $uid, $item);
240                                 $notified = true;
241                         }
242                 }
243
244                 if (self::checkDirectComment($item, $contacts)) {
245                         $notification_type = $notification_type | self::TYPE_DIRECT_COMMENT;
246                         if (!$notified) {
247                                 self::insertNotificationByItem(self::TYPE_DIRECT_COMMENT, $uid, $item);
248                                 $notified = true;
249                         }
250                 }
251
252                 if (!$iscommunity && self::checkDirectCommentedThread($item, $contacts)) {
253                         $notification_type = $notification_type | self::TYPE_DIRECT_THREAD_COMMENT;
254                         if (!$notified) {
255                                 self::insertNotificationByItem(self::TYPE_DIRECT_THREAD_COMMENT, $uid, $item);
256                                 $notified = true;
257                         }
258                 }
259
260                 if (($item['verb'] != Activity::ANNOUNCE) && self::checkCommentedThread($item, $contacts)) {
261                         $notification_type = $notification_type | self::TYPE_THREAD_COMMENT;
262                         if (!$notified) {
263                                 self::insertNotificationByItem(self::TYPE_THREAD_COMMENT, $uid, $item);
264                                 $notified = true;
265                         }
266                 }
267
268                 if (($item['verb'] != Activity::ANNOUNCE) && self::checkCommentedParticipation($item, $contacts)) {
269                         $notification_type = $notification_type | self::TYPE_COMMENT_PARTICIPATION;
270                         if (!$notified) {
271                                 self::insertNotificationByItem(self::TYPE_COMMENT_PARTICIPATION, $uid, $item);
272                                 $notified = true;
273                         }
274                 }
275
276                 if (($item['verb'] != Activity::ANNOUNCE) && self::checkQuoted($item, $contacts)) {
277                         $notification_type = $notification_type | self::TYPE_QUOTED;
278                         if (!$notified) {
279                                 self::insertNotificationByItem(self::TYPE_QUOTED, $uid, $item);
280                                 $notified = true;
281                         }
282                 }
283
284                 if (($item['verb'] != Activity::ANNOUNCE) && self::checkFollowParticipation($item, $contacts)) {
285                         $notification_type = $notification_type | self::TYPE_FOLLOW;
286                         if (!$notified) {
287                                 self::insertNotificationByItem(self::TYPE_FOLLOW, $uid, $item);
288                                 $notified = true;
289                         }
290                 }
291
292                 if (($item['verb'] != Activity::ANNOUNCE) && self::checkActivityParticipation($item, $contacts)) {
293                         $notification_type = $notification_type | self::TYPE_ACTIVITY_PARTICIPATION;
294                         if (!$notified) {
295                                 self::insertNotificationByItem(self::TYPE_ACTIVITY_PARTICIPATION, $uid, $item);
296                         }
297                 }
298
299                 if (empty($notification_type)) {
300                         return;
301                 }
302
303                 // Only create notifications for posts and comments, not for activities
304                 if (($item['gravity'] == Item::GRAVITY_ACTIVITY) && ($item['verb'] != Activity::ANNOUNCE)) {
305                         return;
306                 }
307
308                 Logger::info('Set notification', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'notification-type' => $notification_type]);
309
310                 $fields = ['notification-type' => $notification_type];
311                 Post\User::update($item['uri-id'], $uid, $fields);
312                 self::update($item['uri-id'], $uid, $fields, true);
313         }
314
315         /**
316          * Add a notification entry for a given item array
317          *
318          * @param int   $type User notification type
319          * @param int   $uid  User ID
320          * @param array $item Item array
321          * @return void
322          * @throws Exception
323          */
324         private static function insertNotificationByItem(int $type, int $uid, array $item): void
325         {
326                 if (($item['verb'] != Activity::ANNOUNCE) && ($item['gravity'] == Item::GRAVITY_ACTIVITY) &&
327                         !in_array($type, [self::TYPE_DIRECT_COMMENT, self::TYPE_DIRECT_THREAD_COMMENT])) {
328                         // Activities are only stored when performed on the user's post or comment
329                         return;
330                 }
331
332                 $notification = DI::notificationFactory()->createForUser(
333                         $uid,
334                         $item['vid'],
335                         $type,
336                         $item['author-id'],
337                         $item['gravity'] == Item::GRAVITY_ACTIVITY ? $item['thr-parent-id'] : $item['uri-id'],
338                         $item['parent-uri-id']
339                 );
340
341                 try {
342                         $notification = DI::notification()->save($notification);
343                         Subscription::pushByNotification($notification);
344                 } catch (Exception $e) {
345
346                 }
347         }
348
349         /**
350          * Add a notification entry
351          *
352          * @param int    $actor Public contact ID of the actor
353          * @param string $verb  One of the Activity verb constant values
354          * @param int    $uid   User ID
355          * @return boolean
356          * @throws Exception
357          */
358         public static function insertNotification(int $actor, string $verb, int $uid): bool
359         {
360                 $notification = DI::notificationFactory()->createForRelationship(
361                         $uid,
362                         $actor,
363                         $verb
364                 );
365                 try {
366                         $notification = DI::notification()->save($notification);
367                         Subscription::pushByNotification($notification);
368                         return true;
369                 } catch (Exception $e) {
370                         return false;
371                 }
372         }
373
374         /**
375          * Fetch all profiles (contact URL) of a given user
376          *
377          * @param int $uid User ID
378          *
379          * @return array Profile links
380          * @throws HTTPException\InternalServerErrorException
381          */
382         private static function getProfileForUser(int $uid): array
383         {
384                 $notification_data = ['uid' => $uid, 'profiles' => []];
385                 Hook::callAll('check_item_notification', $notification_data);
386
387                 $profiles = $notification_data['profiles'];
388
389                 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
390                 if (!DBA::isResult($user)) {
391                         return [];
392                 }
393
394                 $owner = DBA::selectFirst('contact', ['url', 'alias'], ['self' => true, 'uid' => $uid]);
395                 if (!DBA::isResult($owner)) {
396                         return [];
397                 }
398
399                 // This is our regular URL format
400                 $profiles[] = $owner['url'];
401
402                 // Now the alias
403                 $profiles[] = $owner['alias'];
404
405                 // Notifications from Diaspora often have a URL in the Diaspora format
406                 $profiles[] = DI::baseUrl() . '/u/' . $user['nickname'];
407
408                 // Validate and add profile links
409                 foreach ($profiles as $key => $profile) {
410                         // Check for invalid profile urls (without scheme, host or path) and remove them
411                         if (empty(parse_url($profile, PHP_URL_SCHEME)) || empty(parse_url($profile, PHP_URL_HOST)) || empty(parse_url($profile, PHP_URL_PATH))) {
412                                 unset($profiles[$key]);
413                                 continue;
414                         }
415
416                         // Add the normalized form
417                         $profile    = Strings::normaliseLink($profile);
418                         $profiles[] = $profile;
419
420                         // Add the SSL form
421                         $profile    = str_replace('http://', 'https://', $profile);
422                         $profiles[] = $profile;
423                 }
424
425                 return array_unique($profiles);
426         }
427
428         /**
429          * Check for a "shared" notification for every new post of contacts from the given user
430          *
431          * @param array $item
432          * @param int   $uid User ID
433          * @return bool A contact had shared something
434          * @throws Exception
435          */
436         private static function checkShared(array $item, int $uid): bool
437         {
438                 // Only check on original posts and reshare ("announce") activities, otherwise return
439                 if (($item['gravity'] != Item::GRAVITY_PARENT) && ($item['verb'] != Activity::ANNOUNCE)) {
440                         return false;
441                 }
442
443                 // Don't notify about reshares by communities of our own posts or each time someone comments
444                 if (($item['verb'] == Activity::ANNOUNCE) && DBA::exists('contact', ['id' => $item['contact-id'], 'contact-type' => Contact::TYPE_COMMUNITY])) {
445                         $post = Post::selectFirst(['origin', 'gravity'], ['uri-id' => $item['thr-parent-id'], 'uid' => $uid]);
446                         if (!$post || $post['origin'] || ($post['gravity'] != Item::GRAVITY_PARENT)) {
447                                 return false;
448                         }
449                 }
450
451                 // Only check on posts by the user itself
452                 $cdata = Contact::getPublicAndUserContactID($item['contact-id'], $item['uid']);
453                 if (empty($cdata['user']) || ($item['author-id'] != $cdata['public'])) {
454                         return false;
455                 }
456
457                 // Check if the contact posted or shared something directly
458                 if (DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true])) {
459                         return true;
460                 }
461
462                 return false;
463         }
464
465         /**
466          * Check for an implicit mention (only in tags, not in body) of the given user
467          *
468          * @param array $item
469          * @param array $profiles Profile links
470          * @return bool The user is mentioned
471          * @throws Exception
472          */
473         private static function checkImplicitMention(array $item, array $profiles): bool
474         {
475                 $mentions = Tag::getByURIId($item['uri-id'], [Tag::IMPLICIT_MENTION]);
476                 foreach ($mentions as $mention) {
477                         foreach ($profiles as $profile) {
478                                 if (Strings::compareLink($profile, $mention['url'])) {
479                                         return true;
480                                 }
481                         }
482                 }
483
484                 return false;
485         }
486
487         /**
488          * Check for an explicit mention (tag and body) of the given user
489          *
490          * @param array $item
491          * @param array $profiles Profile links
492          * @return bool The user is mentioned
493          * @throws Exception
494          */
495         private static function checkExplicitMention(array $item, array $profiles): bool
496         {
497                 $mentions = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
498                 foreach ($mentions as $mention) {
499                         foreach ($profiles as $profile) {
500                                 if (Strings::compareLink($profile, $mention['url'])) {
501                                         return true;
502                                 }
503                         }
504                 }
505
506                 return false;
507         }
508
509         /**
510          * Check if the given user had created this thread
511          *
512          * @param array $item
513          * @param array $contacts Array of contact IDs
514          * @return bool The user had created this thread
515          * @throws Exception
516          */
517         private static function checkCommentedThread(array $item, array $contacts): bool
518         {
519                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_PARENT];
520                 return Post::exists($condition);
521         }
522
523         /**
524          * Check for a direct comment to a post of the given user
525          *
526          * @param array $item
527          * @param array $contacts Array of contact IDs
528          * @return bool The item is a direct comment to a user comment
529          * @throws Exception
530          */
531         private static function checkDirectComment(array $item, array $contacts): bool
532         {
533                 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_COMMENT];
534                 return Post::exists($condition);
535         }
536
537         /**
538          * Check for a direct comment to the starting post of the given user
539          *
540          * @param array $item
541          * @param array $contacts Array of contact IDs
542          * @return bool The user had created this thread
543          * @throws Exception
544          */
545         private static function checkDirectCommentedThread(array $item, array $contacts): bool
546         {
547                 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_PARENT];
548                 return Post::exists($condition);
549         }
550
551         /**
552          *  Check if the user had commented in this thread
553          *
554          * @param array $item
555          * @param array $contacts Array of contact IDs
556          * @return bool The user had commented in the thread
557          * @throws Exception
558          */
559         private static function checkCommentedParticipation(array $item, array $contacts): bool
560         {
561                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_COMMENT];
562                 return Post::exists($condition);
563         }
564
565         /**
566          * Check if the user follows this thread
567          *
568          * @param array $item
569          * @param array $contacts Array of contact IDs
570          * @return bool The user follows the thread
571          * @throws Exception
572          */
573         private static function checkFollowParticipation(array $item, array $contacts): bool
574         {
575                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_ACTIVITY, 'verb' => Activity::FOLLOW];
576                 return Post::exists($condition);
577         }
578
579         /**
580          * Check if the user had interacted in this thread (Like, Dislike, ...)
581          *
582          * @param array $item
583          * @param array $contacts Array of contact IDs
584          * @return bool The user had interacted in the thread
585          * @throws Exception
586          */
587         private static function checkActivityParticipation(array $item, array $contacts): bool
588         {
589                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_ACTIVITY];
590                 return Post::exists($condition);
591         }
592
593         /**
594          * Check for a quoted post of a post of the given user
595          *
596          * @param array $item
597          * @param array $contacts Array of contact IDs
598          * @return bool The item is a quoted post of a user's post or comment
599          * @throws Exception
600          */
601         private static function checkQuoted(array $item, array $contacts): bool
602         {
603                 if (empty($item['quote-uri-id'])) {
604                         return false;
605                 }
606                 $condition = ['uri-id' => $item['quote-uri-id'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => [item::GRAVITY_PARENT, Item::GRAVITY_COMMENT]];
607                 return Post::exists($condition);
608         }
609
610         
611 }