]> git.mxchange.org Git - friendica.git/blob - src/Model/Post/UserNotification.php
Merge pull request #11997 from Quix0r/rewrite/gravity-constants
[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\Item;
34 use Friendica\Model\Post;
35 use Friendica\Model\Subscription;
36 use Friendica\Model\Tag;
37 use Friendica\Model\User;
38 use Friendica\Network\HTTPException;
39 use Friendica\Protocol\Activity;
40 use Friendica\Util\Strings;
41
42 class UserNotification
43 {
44         // Notification types
45         const TYPE_NONE                   = 0;
46         const TYPE_EXPLICIT_TAGGED        = 1;
47         const TYPE_IMPLICIT_TAGGED        = 2;
48         const TYPE_THREAD_COMMENT         = 4;
49         const TYPE_DIRECT_COMMENT         = 8;
50         const TYPE_COMMENT_PARTICIPATION  = 16;
51         const TYPE_ACTIVITY_PARTICIPATION = 32;
52         const TYPE_DIRECT_THREAD_COMMENT  = 64;
53         const TYPE_SHARED                 = 128;
54         const TYPE_FOLLOW                 = 256;
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']);
182                 if (in_array($user['account-type'], [User::ACCOUNT_TYPE_COMMUNITY, User::ACCOUNT_TYPE_RELAY])) {
183                         return;
184                 }
185
186                 $author = Contact::getById($item['author-id'], ['contact-type']);
187                 if (empty($author)) {
188                         return;
189                 }
190
191                 $notification_type = self::TYPE_NONE;
192
193                 if (self::checkShared($item, $uid)) {
194                         $notification_type = $notification_type | self::TYPE_SHARED;
195                         self::insertNotificationByItem(self::TYPE_SHARED, $uid, $item);
196                         $notified = true;
197                 } elseif ($author['contact-type'] == Contact::TYPE_COMMUNITY) {
198                         return;
199                 } else {
200                         $notified = false;
201                 }
202
203                 $profiles = self::getProfileForUser($uid);
204
205                 // Fetch all contacts for the given profiles
206                 $contacts    = [];
207                 $iscommunity = false;
208
209                 $ret = DBA::select('contact', ['id', 'contact-type'], ['uid' => 0, 'nurl' => $profiles]);
210                 while ($contact = DBA::fetch($ret)) {
211                         $contacts[] = $contact['id'];
212
213                         if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
214                                 $iscommunity = true;
215                         }
216                 }
217                 DBA::close($ret);
218
219                 // Don't create notifications for user's posts
220                 if (in_array($item['author-id'], $contacts)) {
221                         return;
222                 }
223
224                 if (($item['verb'] != Activity::ANNOUNCE) && self::checkExplicitMention($item, $profiles)) {
225                         $notification_type = $notification_type | self::TYPE_EXPLICIT_TAGGED;
226                         if (!$notified) {
227                                 self::insertNotificationByItem(self::TYPE_EXPLICIT_TAGGED, $uid, $item);
228                                 $notified = true;
229                         }
230                 }
231
232                 if (($item['verb'] != Activity::ANNOUNCE) && self::checkImplicitMention($item, $profiles)) {
233                         $notification_type = $notification_type | self::TYPE_IMPLICIT_TAGGED;
234                         if (!$notified) {
235                                 self::insertNotificationByItem(self::TYPE_IMPLICIT_TAGGED, $uid, $item);
236                                 $notified = true;
237                         }
238                 }
239
240                 if (self::checkDirectComment($item, $contacts)) {
241                         $notification_type = $notification_type | self::TYPE_DIRECT_COMMENT;
242                         if (!$notified) {
243                                 self::insertNotificationByItem(self::TYPE_DIRECT_COMMENT, $uid, $item);
244                                 $notified = true;
245                         }
246                 }
247
248                 if (!$iscommunity && self::checkDirectCommentedThread($item, $contacts)) {
249                         $notification_type = $notification_type | self::TYPE_DIRECT_THREAD_COMMENT;
250                         if (!$notified) {
251                                 self::insertNotificationByItem(self::TYPE_DIRECT_THREAD_COMMENT, $uid, $item);
252                                 $notified = true;
253                         }
254                 }
255
256                 if (($item['verb'] != Activity::ANNOUNCE) && self::checkCommentedThread($item, $contacts)) {
257                         $notification_type = $notification_type | self::TYPE_THREAD_COMMENT;
258                         if (!$notified) {
259                                 self::insertNotificationByItem(self::TYPE_THREAD_COMMENT, $uid, $item);
260                                 $notified = true;
261                         }
262                 }
263
264                 if (($item['verb'] != Activity::ANNOUNCE) && self::checkCommentedParticipation($item, $contacts)) {
265                         $notification_type = $notification_type | self::TYPE_COMMENT_PARTICIPATION;
266                         if (!$notified) {
267                                 self::insertNotificationByItem(self::TYPE_COMMENT_PARTICIPATION, $uid, $item);
268                                 $notified = true;
269                         }
270                 }
271
272                 if (($item['verb'] != Activity::ANNOUNCE) && self::checkFollowParticipation($item, $contacts)) {
273                         $notification_type = $notification_type | self::TYPE_FOLLOW;
274                         if (!$notified) {
275                                 self::insertNotificationByItem(self::TYPE_FOLLOW, $uid, $item);
276                                 $notified = true;
277                         }
278                 }
279
280                 if (($item['verb'] != Activity::ANNOUNCE) && self::checkActivityParticipation($item, $contacts)) {
281                         $notification_type = $notification_type | self::TYPE_ACTIVITY_PARTICIPATION;
282                         if (!$notified) {
283                                 self::insertNotificationByItem(self::TYPE_ACTIVITY_PARTICIPATION, $uid, $item);
284                         }
285                 }
286
287                 if (empty($notification_type)) {
288                         return;
289                 }
290
291                 // Only create notifications for posts and comments, not for activities
292                 if (($item['gravity'] == Item::GRAVITY_ACTIVITY) && ($item['verb'] != Activity::ANNOUNCE)) {
293                         return;
294                 }
295
296                 Logger::info('Set notification', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'notification-type' => $notification_type]);
297
298                 $fields = ['notification-type' => $notification_type];
299                 Post\User::update($item['uri-id'], $uid, $fields);
300                 self::update($item['uri-id'], $uid, $fields, true);
301         }
302
303         /**
304          * Add a notification entry for a given item array
305          *
306          * @param int   $type User notification type
307          * @param int   $uid  User ID
308          * @param array $item Item array
309          * @return void
310          * @throws Exception
311          */
312         private static function insertNotificationByItem(int $type, int $uid, array $item): void
313         {
314                 if (($item['verb'] != Activity::ANNOUNCE) && ($item['gravity'] == Item::GRAVITY_ACTIVITY) &&
315                         !in_array($type, [self::TYPE_DIRECT_COMMENT, self::TYPE_DIRECT_THREAD_COMMENT])) {
316                         // Activities are only stored when performed on the user's post or comment
317                         return;
318                 }
319
320                 $notification = DI::notificationFactory()->createForUser(
321                         $uid,
322                         $item['vid'],
323                         $type,
324                         $item['author-id'],
325                         $item['gravity'] == Item::GRAVITY_ACTIVITY ? $item['thr-parent-id'] : $item['uri-id'],
326                         $item['parent-uri-id']
327                 );
328
329                 try {
330                         $notification = DI::notification()->save($notification);
331                         Subscription::pushByNotification($notification);
332                 } catch (Exception $e) {
333
334                 }
335         }
336
337         /**
338          * Add a notification entry
339          *
340          * @param int    $actor Public contact ID of the actor
341          * @param string $verb  One of the Activity verb constant values
342          * @param int    $uid   User ID
343          * @return boolean
344          * @throws Exception
345          */
346         public static function insertNotification(int $actor, string $verb, int $uid): bool
347         {
348                 $notification = DI::notificationFactory()->createForRelationship(
349                         $uid,
350                         $actor,
351                         $verb
352                 );
353                 try {
354                         $notification = DI::notification()->save($notification);
355                         Subscription::pushByNotification($notification);
356                         return true;
357                 } catch (Exception $e) {
358                         return false;
359                 }
360         }
361
362         /**
363          * Fetch all profiles (contact URL) of a given user
364          *
365          * @param int $uid User ID
366          *
367          * @return array Profile links
368          * @throws HTTPException\InternalServerErrorException
369          */
370         private static function getProfileForUser(int $uid): array
371         {
372                 $notification_data = ['uid' => $uid, 'profiles' => []];
373                 Hook::callAll('check_item_notification', $notification_data);
374
375                 $profiles = $notification_data['profiles'];
376
377                 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
378                 if (!DBA::isResult($user)) {
379                         return [];
380                 }
381
382                 $owner = DBA::selectFirst('contact', ['url', 'alias'], ['self' => true, 'uid' => $uid]);
383                 if (!DBA::isResult($owner)) {
384                         return [];
385                 }
386
387                 // This is our regular URL format
388                 $profiles[] = $owner['url'];
389
390                 // Now the alias
391                 $profiles[] = $owner['alias'];
392
393                 // Notifications from Diaspora often have a URL in the Diaspora format
394                 $profiles[] = DI::baseUrl() . '/u/' . $user['nickname'];
395
396                 // Validate and add profile links
397                 foreach ($profiles as $key => $profile) {
398                         // Check for invalid profile urls (without scheme, host or path) and remove them
399                         if (empty(parse_url($profile, PHP_URL_SCHEME)) || empty(parse_url($profile, PHP_URL_HOST)) || empty(parse_url($profile, PHP_URL_PATH))) {
400                                 unset($profiles[$key]);
401                                 continue;
402                         }
403
404                         // Add the normalized form
405                         $profile    = Strings::normaliseLink($profile);
406                         $profiles[] = $profile;
407
408                         // Add the SSL form
409                         $profile    = str_replace('http://', 'https://', $profile);
410                         $profiles[] = $profile;
411                 }
412
413                 return array_unique($profiles);
414         }
415
416         /**
417          * Check for a "shared" notification for every new post of contacts from the given user
418          *
419          * @param array $item
420          * @param int   $uid User ID
421          * @return bool A contact had shared something
422          * @throws Exception
423          */
424         private static function checkShared(array $item, int $uid): bool
425         {
426                 // Only check on original posts and reshare ("announce") activities, otherwise return
427                 if (($item['gravity'] != Item::GRAVITY_PARENT) && ($item['verb'] != Activity::ANNOUNCE)) {
428                         return false;
429                 }
430
431                 // Don't notify about reshares by communities of our own posts or each time someone comments
432                 if (($item['verb'] == Activity::ANNOUNCE) && DBA::exists('contact', ['id' => $item['contact-id'], 'contact-type' => Contact::TYPE_COMMUNITY])) {
433                         $post = Post::selectFirst(['origin', 'gravity'], ['uri-id' => $item['thr-parent-id'], 'uid' => $uid]);
434                         if ($post['origin'] || ($post['gravity'] != Item::GRAVITY_PARENT)) {
435                                 return false;
436                         }
437                 }
438
439                 // Check if the contact posted or shared something directly
440                 if (DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true])) {
441                         return true;
442                 }
443
444                 return false;
445         }
446
447         /**
448          * Check for an implicit mention (only in tags, not in body) of the given user
449          *
450          * @param array $item
451          * @param array $profiles Profile links
452          * @return bool The user is mentioned
453          * @throws Exception
454          */
455         private static function checkImplicitMention(array $item, array $profiles): bool
456         {
457                 $mentions = Tag::getByURIId($item['uri-id'], [Tag::IMPLICIT_MENTION]);
458                 foreach ($mentions as $mention) {
459                         foreach ($profiles as $profile) {
460                                 if (Strings::compareLink($profile, $mention['url'])) {
461                                         return true;
462                                 }
463                         }
464                 }
465
466                 return false;
467         }
468
469         /**
470          * Check for an explicit mention (tag and body) of the given user
471          *
472          * @param array $item
473          * @param array $profiles Profile links
474          * @return bool The user is mentioned
475          * @throws Exception
476          */
477         private static function checkExplicitMention(array $item, array $profiles): bool
478         {
479                 $mentions = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
480                 foreach ($mentions as $mention) {
481                         foreach ($profiles as $profile) {
482                                 if (Strings::compareLink($profile, $mention['url'])) {
483                                         return true;
484                                 }
485                         }
486                 }
487
488                 return false;
489         }
490
491         /**
492          * Check if the given user had created this thread
493          *
494          * @param array $item
495          * @param array $contacts Array of contact IDs
496          * @return bool The user had created this thread
497          * @throws Exception
498          */
499         private static function checkCommentedThread(array $item, array $contacts): bool
500         {
501                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_PARENT];
502                 return Post::exists($condition);
503         }
504
505         /**
506          * Check for a direct comment to a post of the given user
507          *
508          * @param array $item
509          * @param array $contacts Array of contact IDs
510          * @return bool The item is a direct comment to a user comment
511          * @throws Exception
512          */
513         private static function checkDirectComment(array $item, array $contacts): bool
514         {
515                 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_COMMENT];
516                 return Post::exists($condition);
517         }
518
519         /**
520          * Check for a direct comment to the starting post of the given user
521          *
522          * @param array $item
523          * @param array $contacts Array of contact IDs
524          * @return bool The user had created this thread
525          * @throws Exception
526          */
527         private static function checkDirectCommentedThread(array $item, array $contacts): bool
528         {
529                 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_PARENT];
530                 return Post::exists($condition);
531         }
532
533         /**
534          *  Check if the user had commented in this thread
535          *
536          * @param array $item
537          * @param array $contacts Array of contact IDs
538          * @return bool The user had commented in the thread
539          * @throws Exception
540          */
541         private static function checkCommentedParticipation(array $item, array $contacts): bool
542         {
543                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_COMMENT];
544                 return Post::exists($condition);
545         }
546
547         /**
548          * Check if the user follows this thread
549          *
550          * @param array $item
551          * @param array $contacts Array of contact IDs
552          * @return bool The user follows the thread
553          * @throws Exception
554          */
555         private static function checkFollowParticipation(array $item, array $contacts): bool
556         {
557                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_ACTIVITY, 'verb' => Activity::FOLLOW];
558                 return Post::exists($condition);
559         }
560
561         /**
562          * Check if the user had interacted in this thread (Like, Dislike, ...)
563          *
564          * @param array $item
565          * @param array $contacts Array of contact IDs
566          * @return bool The user had interacted in the thread
567          * @throws Exception
568          */
569         private static function checkActivityParticipation(array $item, array $contacts): bool
570         {
571                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => Item::GRAVITY_ACTIVITY];
572                 return Post::exists($condition);
573         }
574 }