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