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