]> git.mxchange.org Git - friendica.git/blob - src/Model/Post/UserNotification.php
065cba44ca706f72f3e034a2b4b6eee64fda54d8
[friendica.git] / src / Model / Post / UserNotification.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, 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\Network\HTTPException;
37 use Friendica\Protocol\Activity;
38 use Friendica\Util\DateTimeFormat;
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
54         /**
55          * Insert a new user notification entry
56          *
57          * @param integer $uri_id
58          * @param integer $uid
59          * @param array   $data
60          * @return bool   success
61          * @throws Exception
62          */
63         public static function insert(int $uri_id, int $uid, array $data = []): bool
64         {
65                 if (empty($uri_id)) {
66                         throw new BadMethodCallException('Empty URI_id');
67                 }
68
69                 $fields = DBStructure::getFieldsForTable('post-user-notification', $data);
70
71                 $fields['uri-id'] = $uri_id;
72                 $fields['uid']    = $uid;
73
74                 return DBA::insert('post-user-notification', $fields, Database::INSERT_IGNORE);
75         }
76
77         /**
78          * Update a user notification entry
79          *
80          * @param integer $uri_id
81          * @param integer $uid
82          * @param array   $data
83          * @param bool    $insert_if_missing
84          * @return bool
85          * @throws Exception
86          */
87         public static function update(int $uri_id, int $uid, array $data = [], bool $insert_if_missing = false): bool
88         {
89                 if (empty($uri_id)) {
90                         throw new BadMethodCallException('Empty URI_id');
91                 }
92
93                 $fields = DBStructure::getFieldsForTable('post-user-notification', $data);
94
95                 // Remove the key fields
96                 unset($fields['uri-id']);
97                 unset($fields['uid']);
98
99                 if (empty($fields)) {
100                         return true;
101                 }
102
103                 return DBA::update('post-user-notification', $fields, ['uri-id' => $uri_id, 'uid' => $uid], $insert_if_missing ? true : []);
104         }
105
106         /**
107          * Delete a row from the post-user-notification table
108          *
109          * @param array $conditions  Field condition(s)
110          * @param array $options     - cascade: If true we delete records in other tables that depend on the one we're deleting through
111          *                           relations (default: true)
112          *
113          * @return boolean was the deletion successful?
114          * @throws Exception
115          */
116         public static function delete(array $conditions, array $options = []): bool
117         {
118                 return DBA::delete('post-user-notification', $conditions, $options);
119         }
120
121         /**
122          * Checks an item for notifications and sets the "notification-type" field
123          *
124          * @ToDo:
125          * - Check for mentions in posts with "uid=0" where the user hadn't interacted before
126          *
127          * @param int $uri_id URI ID
128          * @param int $uid    user ID
129          * @throws Exception
130          */
131         public static function setNotification(int $uri_id, int $uid)
132         {
133                 $fields = ['id', 'uri-id', 'parent-uri-id', 'uid', 'body', 'parent', 'gravity', 'vid', 'gravity',
134                            'private', 'contact-id', 'thr-parent', 'thr-parent-id', 'parent-uri-id', 'parent-uri', 'author-id', 'verb'];
135                 $item   = Post::selectFirst($fields, ['uri-id' => $uri_id, 'uid' => $uid, 'origin' => false]);
136                 if (!DBA::isResult($item)) {
137                         return;
138                 }
139
140                 // "Activity::FOLLOW" is an automated activity, so we ignore it here
141                 if ($item['verb'] == Activity::FOLLOW) {
142                         return;
143                 }
144
145                 if ($item['uid'] == 0) {
146                         $uids = [];
147                 } else {
148                         // Always include the item user
149                         $uids = [$item['uid']];
150                 }
151
152                 // Add every user who participated so far in this thread
153                 // This can only happen with participations on global items. (means: uid = 0)
154                 $users = DBA::p("SELECT DISTINCT(`contact-uid`) AS `uid` FROM `post-user-view`
155                         WHERE `contact-uid` != 0 AND `parent-uri-id` = ? AND `uid` = ?", $item['parent-uri-id'], $uid);
156                 while ($user = DBA::fetch($users)) {
157                         $uids[] = $user['uid'];
158                 }
159                 DBA::close($users);
160
161                 foreach (array_unique($uids) as $uid) {
162                         self::setNotificationForUser($item, $uid);
163                 }
164         }
165
166         /**
167          * Checks an item for notifications for the given user and sets the "notification-type" field
168          *
169          * @param array $item Item array
170          * @param int   $uid  User ID
171          * @throws HTTPException\InternalServerErrorException
172          */
173         private static function setNotificationForUser(array $item, int $uid)
174         {
175                 if (Post\ThreadUser::getIgnored($item['parent-uri-id'], $uid)) {
176                         return;
177                 }
178
179                 $notification_type = self::TYPE_NONE;
180
181                 if (self::checkShared($item, $uid)) {
182                         $notification_type = $notification_type | self::TYPE_SHARED;
183                         self::insertNotificationByItem(self::TYPE_SHARED, $uid, $item);
184                         $notified = true;
185                 } else {
186                         $notified = false;
187                 }
188
189                 $profiles = self::getProfileForUser($uid);
190
191                 // Fetch all contacts for the given profiles
192                 $contacts = [];
193
194                 $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
195                 while ($contact = DBA::fetch($ret)) {
196                         $contacts[] = $contact['id'];
197                 }
198                 DBA::close($ret);
199
200                 // Don't create notifications for user's posts
201                 if (in_array($item['author-id'], $contacts)) {
202                         return;
203                 }
204
205                 if (self::checkExplicitMention($item, $profiles)) {
206                         $notification_type = $notification_type | self::TYPE_EXPLICIT_TAGGED;
207                         if (!$notified) {
208                                 self::insertNotificationByItem(self::TYPE_EXPLICIT_TAGGED, $uid, $item);
209                                 $notified = true;
210                         }
211                 }
212
213                 if (self::checkImplicitMention($item, $profiles)) {
214                         $notification_type = $notification_type | self::TYPE_IMPLICIT_TAGGED;
215                         if (!$notified) {
216                                 self::insertNotificationByItem(self::TYPE_IMPLICIT_TAGGED, $uid, $item);
217                                 $notified = true;
218                         }
219                 }
220
221                 if (self::checkDirectComment($item, $contacts)) {
222                         $notification_type = $notification_type | self::TYPE_DIRECT_COMMENT;
223                         if (!$notified) {
224                                 self::insertNotificationByItem(self::TYPE_DIRECT_COMMENT, $uid, $item);
225                                 $notified = true;
226                         }
227                 }
228
229                 if (self::checkDirectCommentedThread($item, $contacts)) {
230                         $notification_type = $notification_type | self::TYPE_DIRECT_THREAD_COMMENT;
231                         if (!$notified) {
232                                 self::insertNotificationByItem(self::TYPE_DIRECT_THREAD_COMMENT, $uid, $item);
233                                 $notified = true;
234                         }
235                 }
236
237                 if (self::checkCommentedThread($item, $contacts)) {
238                         $notification_type = $notification_type | self::TYPE_THREAD_COMMENT;
239                         if (!$notified) {
240                                 self::insertNotificationByItem(self::TYPE_THREAD_COMMENT, $uid, $item);
241                                 $notified = true;
242                         }
243                 }
244
245                 if (self::checkCommentedParticipation($item, $contacts)) {
246                         $notification_type = $notification_type | self::TYPE_COMMENT_PARTICIPATION;
247                         if (!$notified) {
248                                 self::insertNotificationByItem(self::TYPE_COMMENT_PARTICIPATION, $uid, $item);
249                                 $notified = true;
250                         }
251                 }
252
253                 if (self::checkActivityParticipation($item, $contacts)) {
254                         $notification_type = $notification_type | self::TYPE_ACTIVITY_PARTICIPATION;
255                         if (!$notified) {
256                                 self::insertNotificationByItem(self::TYPE_ACTIVITY_PARTICIPATION, $uid, $item);
257                         }
258                 }
259
260                 // Only create notifications for posts and comments, not for activities
261                 if (empty($notification_type) || !in_array($item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT])) {
262                         return;
263                 }
264
265                 Logger::info('Set notification', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'notification-type' => $notification_type]);
266
267                 $fields = ['notification-type' => $notification_type];
268                 Post\User::update($item['uri-id'], $uid, $fields);
269                 self::update($item['uri-id'], $uid, $fields, true);
270         }
271
272         /**
273          * Add a notification entry for a given item array
274          *
275          * @param int   $type User notification type
276          * @param int   $uid  User ID
277          * @param array $item Item array
278          * @return void
279          * @throws Exception
280          */
281         private static function insertNotificationByItem(int $type, int $uid, array $item): void
282         {
283                 if (($item['gravity'] == GRAVITY_ACTIVITY) &&
284                         !in_array($type, [self::TYPE_DIRECT_COMMENT, self::TYPE_DIRECT_THREAD_COMMENT])) {
285                         // Activities are only stored when performed on the user's post or comment
286                         return;
287                 }
288
289                 $fields = [
290                         'uid' => $uid,
291                         'vid' => $item['vid'],
292                         'type' => $type,
293                         'actor-id' => $item['author-id'],
294                         'parent-uri-id' => $item['parent-uri-id'],
295                         'created' => DateTimeFormat::utcNow(),
296                 ];
297
298                 if ($item['gravity'] == GRAVITY_ACTIVITY) {
299                         $fields['target-uri-id'] = $item['thr-parent-id'];
300                 } else {
301                         $fields['target-uri-id'] = $item['uri-id'];
302                 }
303
304                 if (DBA::insert('notification', $fields, Database::INSERT_IGNORE)) {
305                         $id = DBA::lastInsertId();
306                         if (!empty($id)) {
307                                 Subscription::pushByNotificationId($id);
308                         }
309                 }
310         }
311
312         /**
313          * Add a notification entry
314          *
315          * @param int $actor Contact ID of the actor
316          * @param int $vid   Verb ID
317          * @param int $uid   User ID
318          * @return boolean
319          * @throws Exception
320          */
321         public static function insertNotification(int $actor, int $vid, int $uid): bool
322         {
323                 $fields = [
324                         'uid' => $uid,
325                         'vid' => $vid,
326                         'type' => self::TYPE_NONE,
327                         'actor-id' => $actor,
328                         'created' => DateTimeFormat::utcNow(),
329                 ];
330
331                 $ret = DBA::insert('notification', $fields, Database::INSERT_IGNORE);
332                 if ($ret) {
333                         $id = DBA::lastInsertId();
334                         if (!empty($id)) {
335                                 Subscription::pushByNotificationId($id);
336                         }
337                 }
338                 return $ret;
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                 // The following check doesn't make sense on activities, so quit here
416                 if ($item['verb'] == Activity::ANNOUNCE) {
417                         return false;
418                 }
419
420                 // Check if the contact is a mentioned forum
421                 $tags = DBA::select('tag-view', ['url'], ['uri-id' => $item['uri-id'], 'type' => [Tag::MENTION, Tag::EXCLUSIVE_MENTION]]);
422                 while ($tag = DBA::fetch($tags)) {
423                         $condition = ['nurl' => Strings::normaliseLink($tag['url']), 'uid' => $uid, 'notify_new_posts' => true, 'contact-type' => Contact::TYPE_COMMUNITY];
424                         if (DBA::exists('contact', $condition)) {
425                                 return true;
426                         }
427                 }
428                 DBA::close($tags);
429
430                 return false;
431         }
432
433         /**
434          * Check for an implicit mention (only in tags, not in body) of the given user
435          *
436          * @param array $item
437          * @param array $profiles Profile links
438          * @return bool The user is mentioned
439          * @throws Exception
440          */
441         private static function checkImplicitMention(array $item, array $profiles): bool
442         {
443                 $mentions = Tag::getByURIId($item['uri-id'], [Tag::IMPLICIT_MENTION]);
444                 foreach ($mentions as $mention) {
445                         foreach ($profiles as $profile) {
446                                 if (Strings::compareLink($profile, $mention['url'])) {
447                                         return true;
448                                 }
449                         }
450                 }
451
452                 return false;
453         }
454
455         /**
456          * Check for an explicit mention (tag and body) of the given user
457          *
458          * @param array $item
459          * @param array $profiles Profile links
460          * @return bool The user is mentioned
461          * @throws Exception
462          */
463         private static function checkExplicitMention(array $item, array $profiles): bool
464         {
465                 $mentions = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
466                 foreach ($mentions as $mention) {
467                         foreach ($profiles as $profile) {
468                                 if (Strings::compareLink($profile, $mention['url'])) {
469                                         return true;
470                                 }
471                         }
472                 }
473
474                 return false;
475         }
476
477         /**
478          * Check if the given user had created this thread
479          *
480          * @param array $item
481          * @param array $contacts Array of contact IDs
482          * @return bool The user had created this thread
483          * @throws Exception
484          */
485         private static function checkCommentedThread(array $item, array $contacts): bool
486         {
487                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_PARENT];
488                 return Post::exists($condition);
489         }
490
491         /**
492          * Check for a direct comment to a post of the given user
493          *
494          * @param array $item
495          * @param array $contacts Array of contact IDs
496          * @return bool The item is a direct comment to a user comment
497          * @throws Exception
498          */
499         private static function checkDirectComment(array $item, array $contacts): bool
500         {
501                 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_COMMENT];
502                 return Post::exists($condition);
503         }
504
505         /**
506          * Check for a direct comment to the starting post of the given user
507          *
508          * @param array $item
509          * @param array $contacts Array of contact IDs
510          * @return bool The user had created this thread
511          * @throws Exception
512          */
513         private static function checkDirectCommentedThread(array $item, array $contacts): bool
514         {
515                 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_PARENT];
516                 return Post::exists($condition);
517         }
518
519         /**
520          *  Check if the user had commented in this thread
521          *
522          * @param array $item
523          * @param array $contacts Array of contact IDs
524          * @return bool The user had commented in the thread
525          * @throws Exception
526          */
527         private static function checkCommentedParticipation(array $item, array $contacts): bool
528         {
529                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_COMMENT];
530                 return Post::exists($condition);
531         }
532
533         /**
534          * Check if the user had interacted in this thread (Like, Dislike, ...)
535          *
536          * @param array $item
537          * @param array $contacts Array of contact IDs
538          * @return bool The user had interacted in the thread
539          * @throws Exception
540          */
541         private static function checkActivityParticipation(array $item, array $contacts): bool
542         {
543                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY];
544                 return Post::exists($condition);
545         }
546 }