]> git.mxchange.org Git - friendica.git/blob - src/Model/Post/UserNotification.php
Remove spaces
[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 NOTIF_NONE = 0;
43         const NOTIF_EXPLICIT_TAGGED = 1;
44         const NOTIF_IMPLICIT_TAGGED = 2;
45         const NOTIF_THREAD_COMMENT = 4;
46         const NOTIF_DIRECT_COMMENT = 8;
47         const NOTIF_COMMENT_PARTICIPATION = 16;
48         const NOTIF_ACTIVITY_PARTICIPATION = 32;
49         const NOTIF_DIRECT_THREAD_COMMENT = 64;
50         const NOTIF_SHARED = 128;
51
52
53         /**
54          * Insert a new user notification entry
55          *
56          * @param integer $uri_id
57          * @param integer $uid
58          * @param array   $fields
59          * @return bool   success
60          * @throws \Exception
61          */
62         public static function insert(int $uri_id, int $uid, array $data = [])
63         {
64                 if (empty($uri_id)) {
65                         throw new BadMethodCallException('Empty URI_id');
66                 }
67
68                 $fields = DBStructure::getFieldsForTable('post-user-notification', $data);
69
70                 // Additionally assign the key fields
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)
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
111          *                           - 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 delete successful?
115          * @throws \Exception
116          */
117         public static function delete(array $conditions, array $options = [])
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          * @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          */
130         public static function setNotification(int $uri_id, int $uid)
131         {
132                 $fields = ['id', 'uri-id', 'parent-uri-id', 'uid', 'body', 'parent', 'gravity', 'vid', 'gravity',
133                         'private', 'contact-id', 'thr-parent', 'thr-parent-id', 'parent-uri-id', 'parent-uri', 'author-id', 'verb'];
134                 $item = Post::selectFirst($fields, ['uri-id' => $uri_id, 'uid' => $uid, 'origin' => false]);
135                 if (!DBA::isResult($item)) {
136                         return;
137                 }
138
139                 // "Activity::FOLLOW" is an automated activity, so we ignore it here
140                 if ($item['verb'] == Activity::FOLLOW) {
141                         return;
142                 }
143
144                 if ($item['uid'] == 0) {
145                         $uids = [];
146                 } else {
147                         // Always include the item user
148                         $uids = [$item['uid']];
149                 }
150
151                 // Add every user who participated so far in this thread
152                 // This can only happen with participations on global items. (means: uid = 0)
153                 $users = DBA::p("SELECT DISTINCT(`contact-uid`) AS `uid` FROM `post-user-view`
154                         WHERE `contact-uid` != 0 AND `parent-uri-id` = ? AND `uid` = ?", $item['parent-uri-id'], $uid);
155                 while ($user = DBA::fetch($users)) {
156                         $uids[] = $user['uid'];
157                 }
158                 DBA::close($users);
159
160                 foreach (array_unique($uids) as $uid) {
161                         self::setNotificationForUser($item, $uid);
162                 }
163         }
164
165         /**
166          * Checks an item for notifications for the given user and sets the "notification-type" field
167          *
168          * @param array $item Item array
169          * @param int   $uid  User ID
170          */
171         private static function setNotificationForUser(array $item, int $uid)
172         {
173                 if (Post\ThreadUser::getIgnored($item['parent-uri-id'], $uid)) {
174                         return;
175                 }
176
177                 $notification_type = self::NOTIF_NONE;
178
179                 if (self::checkShared($item, $uid)) {
180                         $notification_type = $notification_type | self::NOTIF_SHARED;
181                         self::insertNoticationByItem(self::NOTIF_SHARED, $uid, $item);
182                         $notified = true;
183                 } else {
184                         $notified = false;
185                 }
186
187                 $profiles = self::getProfileForUser($uid);
188
189                 // Fetch all contacts for the given profiles
190                 $contacts = [];
191                 $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
192                 while ($contact = DBA::fetch($ret)) {
193                         $contacts[] = $contact['id'];
194                 }
195                 DBA::close($ret);
196
197                 // Don't create notifications for user's posts
198                 if (in_array($item['author-id'], $contacts)) {
199                         return;
200                 }
201
202                 if (self::checkExplicitMention($item, $profiles)) {
203                         $notification_type = $notification_type | self::NOTIF_EXPLICIT_TAGGED;
204                         if (!$notified) {
205                                 self::insertNoticationByItem( self::NOTIF_EXPLICIT_TAGGED, $uid, $item);
206                                 $notified = true;
207                         }
208                 }
209
210                 if (self::checkImplicitMention($item, $profiles)) {
211                         $notification_type = $notification_type | self::NOTIF_IMPLICIT_TAGGED;
212                         if (!$notified) {
213                                 self::insertNoticationByItem(self::NOTIF_IMPLICIT_TAGGED, $uid, $item);
214                                 $notified = true;
215                         }
216                 }
217
218                 if (self::checkDirectComment($item, $contacts)) {
219                         $notification_type = $notification_type | self::NOTIF_DIRECT_COMMENT;
220                         if (!$notified) {
221                                 self::insertNoticationByItem(self::NOTIF_DIRECT_COMMENT, $uid, $item);
222                                 $notified = true;
223                         }
224                 }
225
226                 if (self::checkDirectCommentedThread($item, $contacts)) {
227                         $notification_type = $notification_type | self::NOTIF_DIRECT_THREAD_COMMENT;
228                         if (!$notified) {
229                                 self::insertNoticationByItem(self::NOTIF_DIRECT_THREAD_COMMENT, $uid, $item);
230                                 $notified = true;
231                         }
232                 }
233
234                 if (self::checkCommentedThread($item, $contacts)) {
235                         $notification_type = $notification_type | self::NOTIF_THREAD_COMMENT;
236                         if (!$notified) {
237                                 self::insertNoticationByItem(self::NOTIF_THREAD_COMMENT, $uid, $item);
238                                 $notified = true;
239                         }
240                 }
241
242                 if (self::checkCommentedParticipation($item, $contacts)) {
243                         $notification_type = $notification_type | self::NOTIF_COMMENT_PARTICIPATION;
244                         if (!$notified) {
245                                 self::insertNoticationByItem(self::NOTIF_COMMENT_PARTICIPATION, $uid, $item);
246                                 $notified = true;
247                         }
248                 }
249
250                 if (self::checkActivityParticipation($item, $contacts)) {
251                         $notification_type = $notification_type | self::NOTIF_ACTIVITY_PARTICIPATION;
252                         if (!$notified) {
253                                 self::insertNoticationByItem(self::NOTIF_ACTIVITY_PARTICIPATION, $uid, $item);
254                                 $notified = true;
255                         }
256                 }
257
258                 // Only create notifications for posts and comments, not for activities
259                 if (empty($notification_type) || !in_array($item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT])) {
260                         return;
261                 }
262
263                 Logger::info('Set notification', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'notification-type' => $notification_type]);
264
265                 $fields = ['notification-type' => $notification_type];
266                 Post\User::update($item['uri-id'], $uid, $fields);
267                 self::update($item['uri-id'], $uid, $fields, true);
268         }
269
270         /**
271          * Add a notification entry for a given item array
272          *
273          * @param int $type   User notification type
274          * @param int $uid    User ID
275          * @param array $item Item array
276          * @return boolean
277          */
278         private static function insertNoticationByItem(int $type, int $uid, array $item)
279         {
280                 if (($item['gravity'] == GRAVITY_ACTIVITY) &&
281                         !in_array($type, [self::NOTIF_DIRECT_COMMENT, self::NOTIF_DIRECT_THREAD_COMMENT])) {
282                         // Activities are only stored when performed on the user's post or comment
283                         return;
284                 }
285
286                 $fields = [
287                         'uid' => $uid,
288                         'vid' => $item['vid'],
289                         'type' => $type,
290                         'actor-id' => $item['author-id'],
291                         'parent-uri-id' => $item['parent-uri-id'],
292                         'created' => DateTimeFormat::utcNow(),
293                 ];
294
295                 if ($item['gravity'] == GRAVITY_ACTIVITY) {
296                         $fields['target-uri-id'] = $item['thr-parent-id'];
297                 } else {
298                         $fields['target-uri-id'] = $item['uri-id'];
299                 }
300
301                 $ret = DBA::insert('notification', $fields, Database::INSERT_IGNORE);
302                 if ($ret) {
303                         $id = DBA::lastInsertId();
304                         if (!empty($id)) {
305                                 Subscription::pushByNotificationId($id);
306                         }
307                 }
308                 return $ret;
309         }
310
311         /**
312          * Add a notification entry
313          *
314          * @param int $actor Contact ID of the actor
315          * @param int $vid   Verb ID
316          * @param int $uid   User ID
317          * @return boolean
318          */
319         public static function insertNotication(int $actor, int $vid, int $uid)
320         {
321                 $fields = [
322                         'uid' => $uid,
323                         'vid' => $vid,
324                         'type' => self::NOTIF_NONE,
325                         'actor-id' => $actor,
326                         'created' => DateTimeFormat::utcNow(),
327                 ];
328
329                 $ret = DBA::insert('notification', $fields, Database::INSERT_IGNORE);
330                 if ($ret) {
331                         $id = DBA::lastInsertId();
332                         if (!empty($id)) {
333                                 Subscription::pushByNotificationId($id);
334                         }
335                 }
336                 return $ret;
337         }
338
339         /**
340          * Fetch all profiles (contact URL) of a given user
341          * @param int $uid User ID
342          *
343          * @return array Profile links
344          */
345         private static function getProfileForUser(int $uid)
346         {
347                 $notification_data = ['uid' => $uid, 'profiles' => []];
348                 Hook::callAll('check_item_notification', $notification_data);
349
350                 $profiles = $notification_data['profiles'];
351
352                 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
353                 if (!DBA::isResult($user)) {
354                         return [];
355                 }
356
357                 $owner = DBA::selectFirst('contact', ['url', 'alias'], ['self' => true, 'uid' => $uid]);
358                 if (!DBA::isResult($owner)) {
359                         return [];
360                 }
361
362                 // This is our regular URL format
363                 $profiles[] = $owner['url'];
364
365                 // Now the alias
366                 $profiles[] = $owner['alias'];
367
368                 // Notifications from Diaspora are often with an URL in the Diaspora format
369                 $profiles[] = DI::baseUrl() . '/u/' . $user['nickname'];
370
371                 // Validate and add profile links
372                 foreach ($profiles AS $key => $profile) {
373                         // Check for invalid profile urls (without scheme, host or path) and remove them
374                         if (empty(parse_url($profile, PHP_URL_SCHEME)) || empty(parse_url($profile, PHP_URL_HOST)) || empty(parse_url($profile, PHP_URL_PATH))) {
375                                 unset($profiles[$key]);
376                                 continue;
377                         }
378
379                         // Add the normalized form
380                         $profile = Strings::normaliseLink($profile);
381                         $profiles[] = $profile;
382
383                         // Add the SSL form
384                         $profile = str_replace('http://', 'https://', $profile);
385                         $profiles[] = $profile;
386                 }
387
388                 return array_unique($profiles);
389         }
390
391         /**
392          * Check for a "shared" notification for every new post of contacts from the given user
393          * @param array $item
394          * @param int   $uid  User ID
395          * @return bool A contact had shared something
396          */
397         private static function checkShared(array $item, int $uid)
398         {
399                 // Only check on original posts and reshare ("announce") activities, otherwise return
400                 if (($item['gravity'] != GRAVITY_PARENT) && ($item['verb'] != Activity::ANNOUNCE)) {
401                         return false;
402                 }
403
404                 // Check if the contact posted or shared something directly
405                 if (DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true])) {
406                         return true;
407                 }
408
409                 // The following check doesn't make sense on activities, so quit here
410                 if ($item['verb'] == Activity::ANNOUNCE) {
411                         return false;
412                 }
413
414                 // Check if the contact is a mentioned forum
415                 $tags = DBA::select('tag-view', ['url'], ['uri-id' => $item['uri-id'], 'type' => [Tag::MENTION, Tag::EXCLUSIVE_MENTION]]);
416                 while ($tag = DBA::fetch($tags)) {
417                         $condition = ['nurl' => Strings::normaliseLink($tag['url']), 'uid' => $uid, 'notify_new_posts' => true, 'contact-type' => Contact::TYPE_COMMUNITY];
418                         if (DBA::exists('contact', $condition)) {
419                                 return true;
420                         }
421                 }
422                 DBA::close($tags);
423
424                 return false;
425         }
426
427         /**
428          * Check for an implicit mention (only tag, no body) of the given user
429          * @param array $item
430          * @param array $profiles Profile links
431          * @return bool The user is mentioned
432          */
433         private static function checkImplicitMention(array $item, array $profiles)
434         {
435                 $mentions = Tag::getByURIId($item['uri-id'], [Tag::IMPLICIT_MENTION]);
436                 foreach ($mentions as $mention) {
437                         foreach ($profiles as $profile) {
438                                 if (Strings::compareLink($profile, $mention['url'])) {
439                                         return true;
440                                 }
441                         }
442                 }
443
444                 return false;
445         }
446
447         /**
448          * Check for an explicit mention (tag and body) of the given user
449          * @param array $item
450          * @param array $profiles Profile links
451          * @return bool The user is mentioned
452          */
453         private static function checkExplicitMention(array $item, array $profiles)
454         {
455                 $mentions = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
456                 foreach ($mentions as $mention) {
457                         foreach ($profiles as $profile) {
458                                 if (Strings::compareLink($profile, $mention['url'])) {
459                                         return true;
460                                 }
461                         }
462                 }
463
464                 return false;
465         }
466
467         /**
468          * Check if the given user had created this thread
469          * @param array $item
470          * @param array $contacts Array of contact IDs
471          * @return bool The user had created this thread
472          */
473         private static function checkCommentedThread(array $item, array $contacts)
474         {
475                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_PARENT];
476                 return Post::exists($condition);
477         }
478
479         /**
480          * Check for a direct comment to a post of the given user
481          * @param array $item
482          * @param array $contacts Array of contact IDs
483          * @return bool The item is a direct comment to a user comment
484          */
485         private static function checkDirectComment(array $item, array $contacts)
486         {
487                 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_COMMENT];
488                 return Post::exists($condition);
489         }
490
491         /**
492          * Check for a direct comment to the starting post of the given user
493          * @param array $item
494          * @param array $contacts Array of contact IDs
495          * @return bool The user had created this thread
496          */
497         private static function checkDirectCommentedThread(array $item, array $contacts)
498         {
499                 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_PARENT];
500                 return Post::exists($condition);
501         }
502
503         /**
504          *  Check if the user had commented in this thread
505          * @param array $item
506          * @param array $contacts Array of contact IDs
507          * @return bool The user had commented in the thread
508          */
509         private static function checkCommentedParticipation(array $item, array $contacts)
510         {
511                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_COMMENT];
512                 return Post::exists($condition);
513         }
514
515         /**
516          * Check if the user had interacted in this thread (Like, Dislike, ...)
517          * @param array $item
518          * @param array $contacts Array of contact IDs
519          * @return bool The user had interacted in the thread
520          */
521         private static function checkActivityParticipation(array $item, array $contacts)
522         {
523                 $condition = ['parent' => $item['parent'], 'author-id' => $contacts, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY];
524                 return Post::exists($condition);
525         }
526 }