294d91bdcbe9ca05d0eec51834a48dacb0f78003
[friendica.git/.git] / src / Model / Post / UserNotification.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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 Friendica\Core\Logger;
26 use Friendica\Core\Hook;
27 use Friendica\Database\Database;
28 use Friendica\Database\DBA;
29 use Friendica\Database\DBStructure;
30 use Friendica\DI;
31 use Friendica\Model\Contact;
32 use Friendica\Model\Post;
33 use Friendica\Util\Strings;
34 use Friendica\Model\Tag;
35 use Friendica\Protocol\Activity;
36
37
38 class UserNotification
39 {
40         // Notification types
41         const NOTIF_NONE = 0;
42         const NOTIF_EXPLICIT_TAGGED = 1;
43         const NOTIF_IMPLICIT_TAGGED = 2;
44         const NOTIF_THREAD_COMMENT = 4;
45         const NOTIF_DIRECT_COMMENT = 8;
46         const NOTIF_COMMENT_PARTICIPATION = 16;
47         const NOTIF_ACTIVITY_PARTICIPATION = 32;
48         const NOTIF_DIRECT_THREAD_COMMENT = 64;
49         const NOTIF_SHARED = 128;
50
51
52         /**
53          * Insert a new user notification entry
54          *
55          * @param integer $uri_id
56          * @param integer $uid
57          * @param array   $fields
58          * @return bool   success
59          * @throws \Exception
60          */
61         public static function insert(int $uri_id, int $uid, array $data = [])
62         {
63                 if (empty($uri_id)) {
64                         throw new BadMethodCallException('Empty URI_id');
65                 }
66
67                 $fields = DBStructure::getFieldsForTable('post-user-notification', $data);
68
69                 // Additionally assign the key fields
70                 $fields['uri-id'] = $uri_id;
71                 $fields['uid'] = $uid;
72
73                 return DBA::insert('post-user-notification', $fields, Database::INSERT_IGNORE);
74         }
75
76         /**
77          * Update a user notification entry
78          *
79          * @param integer $uri_id
80          * @param integer $uid
81          * @param array   $data
82          * @param bool    $insert_if_missing
83          * @return bool
84          * @throws \Exception
85          */
86         public static function update(int $uri_id, int $uid, array $data = [], bool $insert_if_missing = false)
87         {
88                 if (empty($uri_id)) {
89                         throw new BadMethodCallException('Empty URI_id');
90                 }
91
92                 $fields = DBStructure::getFieldsForTable('post-user-notification', $data);
93
94                 // Remove the key fields
95                 unset($fields['uri-id']);
96                 unset($fields['uid']);
97
98                 if (empty($fields)) {
99                         return true;
100                 }
101
102                 return DBA::update('post-user-notification', $fields, ['uri-id' => $uri_id, 'uid' => $uid], $insert_if_missing ? true : []);
103         }
104
105         /**
106          * Delete a row from the post-user-notification table
107          *
108          * @param array        $conditions Field condition(s)
109          * @param array        $options
110          *                           - 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 delete successful?
114          * @throws \Exception
115          */
116         public static function delete(array $conditions, array $options = [])
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          * @ToDo:
124          * - Check for mentions in posts with "uid=0" where the user hadn't interacted before
125          *
126          * @param int $uri_id URI ID
127          * @param int $uid    user ID
128          */
129         public static function setNotification(int $uri_id, int $uid)
130         {
131                 $fields = ['id', 'uri-id', 'parent-uri-id', 'uid', 'body', 'parent', 'gravity',
132                         'private', 'contact-id', 'thr-parent', 'parent-uri-id', 'parent-uri', 'author-id', 'verb'];
133                 $item = Post::selectFirst($fields, ['uri-id' => $uri_id, 'uid' => $uid, 'origin' => false]);
134                 if (!DBA::isResult($item)) {
135                         return;
136                 }
137
138                 // "Activity::FOLLOW" is an automated activity, so we ignore it here
139                 if ($item['verb'] == Activity::FOLLOW) {
140                         return;
141                 }
142
143                 if ($item['uid'] == 0) {
144                         $uids = [];
145                 } else {
146                         // Always include the item user
147                         $uids = [$item['uid']];
148                 }
149
150                 // Add every user who participated so far in this thread
151                 // This can only happen with participations on global items. (means: uid = 0) 
152                 $users = DBA::p("SELECT DISTINCT(`contact-uid`) AS `uid` FROM `post-view`
153                         WHERE `contact-uid` != 0 AND `parent-uri-id` = ? AND `uid` = ?", $item['parent-uri-id'], $uid);
154                 while ($user = DBA::fetch($users)) {
155                         $uids[] = $user['uid'];
156                 }
157                 DBA::close($users);
158
159                 foreach (array_unique($uids) as $uid) {
160                         self::setNotificationForUser($item, $uid);
161                 }
162         }
163
164         /**
165          * Checks an item for notifications for the given user and sets the "notification-type" field
166          *
167          * @param array $item Item array
168          * @param int   $uid  User ID
169          */
170         private static function setNotificationForUser(array $item, int $uid)
171         {
172                 if (Post\ThreadUser::getIgnored($item['parent-uri-id'], $uid)) {
173                         return;
174                 }
175
176                 $notification_type = self::NOTIF_NONE;
177
178                 if (self::checkShared($item, $uid)) {
179                         $notification_type = $notification_type | self::NOTIF_SHARED;
180                 }
181
182                 $profiles = self::getProfileForUser($uid);
183
184                 // Fetch all contacts for the given profiles
185                 $contacts = [];
186                 $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
187                 while ($contact = DBA::fetch($ret)) {
188                         $contacts[] = $contact['id'];
189                 }
190                 DBA::close($ret);
191
192                 // Don't create notifications for user's posts
193                 if (in_array($item['author-id'], $contacts)) {
194                         return;
195                 }
196
197                 // Only create notifications for posts and comments, not for activities
198                 if (in_array($item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT])) {
199                         if (self::checkImplicitMention($item, $profiles)) {
200                                 $notification_type = $notification_type | self::NOTIF_IMPLICIT_TAGGED;
201                         }
202
203                         if (self::checkExplicitMention($item, $profiles)) {
204                                 $notification_type = $notification_type | self::NOTIF_EXPLICIT_TAGGED;
205                         }
206
207                         if (self::checkCommentedThread($item, $contacts)) {
208                                 $notification_type = $notification_type | self::NOTIF_THREAD_COMMENT;
209                         }
210
211                         if (self::checkDirectComment($item, $contacts)) {
212                                 $notification_type = $notification_type | self::NOTIF_DIRECT_COMMENT;
213                         }
214
215                         if (self::checkDirectCommentedThread($item, $contacts)) {
216                                 $notification_type = $notification_type | self::NOTIF_DIRECT_THREAD_COMMENT;
217                         }
218
219                         if (self::checkCommentedParticipation($item, $contacts)) {
220                                 $notification_type = $notification_type | self::NOTIF_COMMENT_PARTICIPATION;
221                         }
222
223                         if (self::checkActivityParticipation($item, $contacts)) {
224                                 $notification_type = $notification_type | self::NOTIF_ACTIVITY_PARTICIPATION;
225                         }
226                 }
227
228                 if (empty($notification_type)) {
229                         return;
230                 }
231
232                 Logger::info('Set notification', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'notification-type' => $notification_type]);
233
234                 $fields = ['notification-type' => $notification_type];
235                 Post\User::update($item['uri-id'], $uid, $fields);
236                 self::update($item['uri-id'], $uid, $fields, true);
237         }
238
239         /**
240          * Fetch all profiles (contact URL) of a given user
241          * @param int $uid User ID
242          *
243          * @return array Profile links
244          */
245         private static function getProfileForUser(int $uid)
246         {
247                 $notification_data = ['uid' => $uid, 'profiles' => []];
248                 Hook::callAll('check_item_notification', $notification_data);
249
250                 $profiles = $notification_data['profiles'];
251
252                 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
253                 if (!DBA::isResult($user)) {
254                         return [];
255                 }
256
257                 $owner = DBA::selectFirst('contact', ['url', 'alias'], ['self' => true, 'uid' => $uid]);
258                 if (!DBA::isResult($owner)) {
259                         return [];
260                 }
261
262                 // This is our regular URL format
263                 $profiles[] = $owner['url'];
264
265                 // Now the alias
266                 $profiles[] = $owner['alias'];
267
268                 // Notifications from Diaspora are often with an URL in the Diaspora format
269                 $profiles[] = DI::baseUrl() . '/u/' . $user['nickname'];
270
271                 // Validate and add profile links
272                 foreach ($profiles AS $key => $profile) {
273                         // Check for invalid profile urls (without scheme, host or path) and remove them
274                         if (empty(parse_url($profile, PHP_URL_SCHEME)) || empty(parse_url($profile, PHP_URL_HOST)) || empty(parse_url($profile, PHP_URL_PATH))) {
275                                 unset($profiles[$key]);
276                                 continue;
277                         }
278
279                         // Add the normalized form
280                         $profile = Strings::normaliseLink($profile);
281                         $profiles[] = $profile;
282
283                         // Add the SSL form
284                         $profile = str_replace('http://', 'https://', $profile);
285                         $profiles[] = $profile;
286                 }
287
288                 return array_unique($profiles);
289         }
290
291         /**
292          * Check for a "shared" notification for every new post of contacts from the given user
293          * @param array $item
294          * @param int   $uid  User ID
295          * @return bool A contact had shared something
296          */
297         private static function checkShared(array $item, int $uid)
298         {
299                 // Only check on original posts and reshare ("announce") activities, otherwise return
300                 if (($item['gravity'] != GRAVITY_PARENT) && ($item['verb'] != Activity::ANNOUNCE)) {
301                         return false;
302                 }
303
304                 // Check if the contact posted or shared something directly
305                 if (DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true])) {
306                         return true;
307                 }
308
309                 // The following check doesn't make sense on activities, so quit here
310                 if ($item['verb'] == Activity::ANNOUNCE) {
311                         return false;
312                 }
313
314                 // Check if the contact is a mentioned forum
315                 $tags = DBA::select('tag-view', ['url'], ['uri-id' => $item['uri-id'], 'type' => [Tag::MENTION, Tag::EXCLUSIVE_MENTION]]);
316                 while ($tag = DBA::fetch($tags)) {
317                         $condition = ['nurl' => Strings::normaliseLink($tag['url']), 'uid' => $uid, 'notify_new_posts' => true, 'contact-type' => Contact::TYPE_COMMUNITY];
318                         if (DBA::exists('contact', $condition)) {
319                                 return true;
320                         }
321                 }
322                 DBA::close($tags);
323
324                 return false;
325         }
326
327         /**
328          * Check for an implicit mention (only tag, no body) of the given user
329          * @param array $item
330          * @param array $profiles Profile links
331          * @return bool The user is mentioned
332          */
333         private static function checkImplicitMention(array $item, array $profiles)
334         {
335                 $mentions = Tag::getByURIId($item['uri-id'], [Tag::IMPLICIT_MENTION]);
336                 foreach ($mentions as $mention) {
337                         foreach ($profiles as $profile) {
338                                 if (Strings::compareLink($profile, $mention['url'])) {
339                                         return true;
340                                 }
341                         }
342                 }
343
344                 return false;
345         }
346
347         /**
348          * Check for an explicit mention (tag and body) of the given user
349          * @param array $item
350          * @param array $profiles Profile links
351          * @return bool The user is mentioned
352          */
353         private static function checkExplicitMention(array $item, array $profiles)
354         {
355                 $mentions = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
356                 foreach ($mentions as $mention) {
357                         foreach ($profiles as $profile) {
358                                 if (Strings::compareLink($profile, $mention['url'])) {
359                                         return true;
360                                 }
361                         }
362                 }
363
364                 return false;
365         }
366
367         /**
368          * Check if the given user had created this thread
369          * @param array $item
370          * @param array $contacts Array of contact IDs
371          * @return bool The user had created this thread
372          */
373         private static function checkCommentedThread(array $item, array $contacts)
374         {
375                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_PARENT];
376                 return Post::exists($condition);
377         }
378
379         /**
380          * Check for a direct comment to a post of the given user
381          * @param array $item
382          * @param array $contacts Array of contact IDs
383          * @return bool The item is a direct comment to a user comment
384          */
385         private static function checkDirectComment(array $item, array $contacts)
386         {
387                 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_COMMENT];
388                 return Post::exists($condition);
389         }
390
391         /**
392          * Check for a direct comment to the starting post of the given user
393          * @param array $item
394          * @param array $contacts Array of contact IDs
395          * @return bool The user had created this thread
396          */
397         private static function checkDirectCommentedThread(array $item, array $contacts)
398         {
399                 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_PARENT];
400                 return Post::exists($condition);
401         }
402
403         /**
404          *  Check if the user had commented in this thread
405          * @param array $item
406          * @param array $contacts Array of contact IDs
407          * @return bool The user had commented in the thread
408          */
409         private static function checkCommentedParticipation(array $item, array $contacts)
410         {
411                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_COMMENT];
412                 return Post::exists($condition);
413         }
414
415         /**
416          * Check if the user had interacted in this thread (Like, Dislike, ...)
417          * @param array $item
418          * @param array $contacts Array of contact IDs
419          * @return bool The user had interacted in the thread
420          */
421         private static function checkActivityParticipation(array $item, array $contacts)
422         {
423                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY];
424                 return Post::exists($condition);
425         }
426 }