]> git.mxchange.org Git - friendica.git/blob - src/Model/Post/UserNotification.php
3f053e0f5c5cf708ed74a4fcabd912767b32353f
[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\Model\Subscription;
34 use Friendica\Util\Strings;
35 use Friendica\Model\Tag;
36 use Friendica\Protocol\Activity;
37 use Friendica\Util\DateTimeFormat;
38
39 class UserNotification
40 {
41         // Notification types
42         const TYPE_NONE                   = 0;
43         const TYPE_EXPLICIT_TAGGED        = 1;
44         const TYPE_IMPLICIT_TAGGED        = 2;
45         const TYPE_THREAD_COMMENT         = 4;
46         const TYPE_DIRECT_COMMENT         = 8;
47         const TYPE_COMMENT_PARTICIPATION  = 16;
48         const TYPE_ACTIVITY_PARTICIPATION = 32;
49         const TYPE_DIRECT_THREAD_COMMENT  = 64;
50         const TYPE_SHARED                 = 128;
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::TYPE_NONE;
177
178                 if (self::checkShared($item, $uid)) {
179                         $notification_type = $notification_type | self::TYPE_SHARED;
180                         self::insertNoticationByItem(self::TYPE_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::TYPE_EXPLICIT_TAGGED;
203                         if (!$notified) {
204                                 self::insertNoticationByItem( self::TYPE_EXPLICIT_TAGGED, $uid, $item);
205                                 $notified = true;
206                         }
207                 }
208
209                 if (self::checkImplicitMention($item, $profiles)) {
210                         $notification_type = $notification_type | self::TYPE_IMPLICIT_TAGGED;
211                         if (!$notified) {
212                                 self::insertNoticationByItem(self::TYPE_IMPLICIT_TAGGED, $uid, $item);
213                                 $notified = true;
214                         }
215                 }
216
217                 if (self::checkDirectComment($item, $contacts)) {
218                         $notification_type = $notification_type | self::TYPE_DIRECT_COMMENT;
219                         if (!$notified) {
220                                 self::insertNoticationByItem(self::TYPE_DIRECT_COMMENT, $uid, $item);
221                                 $notified = true;
222                         }
223                 }
224
225                 if (self::checkDirectCommentedThread($item, $contacts)) {
226                         $notification_type = $notification_type | self::TYPE_DIRECT_THREAD_COMMENT;
227                         if (!$notified) {
228                                 self::insertNoticationByItem(self::TYPE_DIRECT_THREAD_COMMENT, $uid, $item);
229                                 $notified = true;
230                         }
231                 }
232
233                 if (self::checkCommentedThread($item, $contacts)) {
234                         $notification_type = $notification_type | self::TYPE_THREAD_COMMENT;
235                         if (!$notified) {
236                                 self::insertNoticationByItem(self::TYPE_THREAD_COMMENT, $uid, $item);
237                                 $notified = true;
238                         }
239                 }
240
241                 if (self::checkCommentedParticipation($item, $contacts)) {
242                         $notification_type = $notification_type | self::TYPE_COMMENT_PARTICIPATION;
243                         if (!$notified) {
244                                 self::insertNoticationByItem(self::TYPE_COMMENT_PARTICIPATION, $uid, $item);
245                                 $notified = true;
246                         }
247                 }
248
249                 if (self::checkActivityParticipation($item, $contacts)) {
250                         $notification_type = $notification_type | self::TYPE_ACTIVITY_PARTICIPATION;
251                         if (!$notified) {
252                                 self::insertNoticationByItem(self::TYPE_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::TYPE_DIRECT_COMMENT, self::TYPE_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                 $ret = DBA::insert('notification', $fields, Database::INSERT_IGNORE);
301                 if ($ret) {
302                         $id = DBA::lastInsertId();
303                         if (!empty($id)) {
304                                 Subscription::pushByNotificationId($id);
305                         }
306                 }
307                 return $ret;
308         }
309
310         /**
311          * Add a notification entry
312          *
313          * @param int $actor Contact ID of the actor
314          * @param int $vid   Verb ID
315          * @param int $uid   User ID
316          * @return boolean
317          */
318         public static function insertNotication(int $actor, int $vid, int $uid)
319         {
320                 $fields = [
321                         'uid' => $uid,
322                         'vid' => $vid,
323                         'type' => self::TYPE_NONE,
324                         'actor-id' => $actor,
325                         'created' => DateTimeFormat::utcNow(),
326                 ];
327
328                 $ret = DBA::insert('notification', $fields, Database::INSERT_IGNORE);
329                 if ($ret) {
330                         $id = DBA::lastInsertId();
331                         if (!empty($id)) {
332                                 Subscription::pushByNotificationId($id);
333                         }
334                 }
335                 return $ret;
336         }
337
338         /**
339          * Fetch all profiles (contact URL) of a given user
340          * @param int $uid User ID
341          *
342          * @return array Profile links
343          */
344         private static function getProfileForUser(int $uid)
345         {
346                 $notification_data = ['uid' => $uid, 'profiles' => []];
347                 Hook::callAll('check_item_notification', $notification_data);
348
349                 $profiles = $notification_data['profiles'];
350
351                 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
352                 if (!DBA::isResult($user)) {
353                         return [];
354                 }
355
356                 $owner = DBA::selectFirst('contact', ['url', 'alias'], ['self' => true, 'uid' => $uid]);
357                 if (!DBA::isResult($owner)) {
358                         return [];
359                 }
360
361                 // This is our regular URL format
362                 $profiles[] = $owner['url'];
363
364                 // Now the alias
365                 $profiles[] = $owner['alias'];
366
367                 // Notifications from Diaspora are often with an URL in the Diaspora format
368                 $profiles[] = DI::baseUrl() . '/u/' . $user['nickname'];
369
370                 // Validate and add profile links
371                 foreach ($profiles AS $key => $profile) {
372                         // Check for invalid profile urls (without scheme, host or path) and remove them
373                         if (empty(parse_url($profile, PHP_URL_SCHEME)) || empty(parse_url($profile, PHP_URL_HOST)) || empty(parse_url($profile, PHP_URL_PATH))) {
374                                 unset($profiles[$key]);
375                                 continue;
376                         }
377
378                         // Add the normalized form
379                         $profile = Strings::normaliseLink($profile);
380                         $profiles[] = $profile;
381
382                         // Add the SSL form
383                         $profile = str_replace('http://', 'https://', $profile);
384                         $profiles[] = $profile;
385                 }
386
387                 return array_unique($profiles);
388         }
389
390         /**
391          * Check for a "shared" notification for every new post of contacts from the given user
392          * @param array $item
393          * @param int   $uid  User ID
394          * @return bool A contact had shared something
395          */
396         private static function checkShared(array $item, int $uid)
397         {
398                 // Only check on original posts and reshare ("announce") activities, otherwise return
399                 if (($item['gravity'] != GRAVITY_PARENT) && ($item['verb'] != Activity::ANNOUNCE)) {
400                         return false;
401                 }
402
403                 // Check if the contact posted or shared something directly
404                 if (DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true])) {
405                         return true;
406                 }
407
408                 // The following check doesn't make sense on activities, so quit here
409                 if ($item['verb'] == Activity::ANNOUNCE) {
410                         return false;
411                 }
412
413                 // Check if the contact is a mentioned forum
414                 $tags = DBA::select('tag-view', ['url'], ['uri-id' => $item['uri-id'], 'type' => [Tag::MENTION, Tag::EXCLUSIVE_MENTION]]);
415                 while ($tag = DBA::fetch($tags)) {
416                         $condition = ['nurl' => Strings::normaliseLink($tag['url']), 'uid' => $uid, 'notify_new_posts' => true, 'contact-type' => Contact::TYPE_COMMUNITY];
417                         if (DBA::exists('contact', $condition)) {
418                                 return true;
419                         }
420                 }
421                 DBA::close($tags);
422
423                 return false;
424         }
425
426         /**
427          * Check for an implicit mention (only tag, no body) of the given user
428          * @param array $item
429          * @param array $profiles Profile links
430          * @return bool The user is mentioned
431          */
432         private static function checkImplicitMention(array $item, array $profiles)
433         {
434                 $mentions = Tag::getByURIId($item['uri-id'], [Tag::IMPLICIT_MENTION]);
435                 foreach ($mentions as $mention) {
436                         foreach ($profiles as $profile) {
437                                 if (Strings::compareLink($profile, $mention['url'])) {
438                                         return true;
439                                 }
440                         }
441                 }
442
443                 return false;
444         }
445
446         /**
447          * Check for an explicit mention (tag and body) of the given user
448          * @param array $item
449          * @param array $profiles Profile links
450          * @return bool The user is mentioned
451          */
452         private static function checkExplicitMention(array $item, array $profiles)
453         {
454                 $mentions = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
455                 foreach ($mentions as $mention) {
456                         foreach ($profiles as $profile) {
457                                 if (Strings::compareLink($profile, $mention['url'])) {
458                                         return true;
459                                 }
460                         }
461                 }
462
463                 return false;
464         }
465
466         /**
467          * Check if the given user had created this thread
468          * @param array $item
469          * @param array $contacts Array of contact IDs
470          * @return bool The user had created this thread
471          */
472         private static function checkCommentedThread(array $item, array $contacts)
473         {
474                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_PARENT];
475                 return Post::exists($condition);
476         }
477
478         /**
479          * Check for a direct comment to a post of the given user
480          * @param array $item
481          * @param array $contacts Array of contact IDs
482          * @return bool The item is a direct comment to a user comment
483          */
484         private static function checkDirectComment(array $item, array $contacts)
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          * @param array $item
493          * @param array $contacts Array of contact IDs
494          * @return bool The user had created this thread
495          */
496         private static function checkDirectCommentedThread(array $item, array $contacts)
497         {
498                 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_PARENT];
499                 return Post::exists($condition);
500         }
501
502         /**
503          *  Check if the user had commented in this thread
504          * @param array $item
505          * @param array $contacts Array of contact IDs
506          * @return bool The user had commented in the thread
507          */
508         private static function checkCommentedParticipation(array $item, array $contacts)
509         {
510                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_COMMENT];
511                 return Post::exists($condition);
512         }
513
514         /**
515          * Check if the user had interacted in this thread (Like, Dislike, ...)
516          * @param array $item
517          * @param array $contacts Array of contact IDs
518          * @return bool The user had interacted in the thread
519          */
520         private static function checkActivityParticipation(array $item, array $contacts)
521         {
522                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY];
523                 return Post::exists($condition);
524         }
525 }