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