]> git.mxchange.org Git - friendica.git/blob - src/Module/Conversation/Channel.php
Fixes the score calculation concerning the relation-cid / cid interaction
[friendica.git] / src / Module / Conversation / Channel.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, 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\Module\Conversation;
23
24 use Friendica\App;
25 use Friendica\App\Mode;
26 use Friendica\BaseModule;
27 use Friendica\Content\BoundariesPager;
28 use Friendica\Content\Conversation;
29 use Friendica\Content\Feature;
30 use Friendica\Content\Nav;
31 use Friendica\Content\Text\HTML;
32 use Friendica\Content\Widget;
33 use Friendica\Content\Widget\TrendingTags;
34 use Friendica\Core\Cache\Capability\ICanCache;
35 use Friendica\Core\Cache\Enum\Duration;
36 use Friendica\Core\Config\Capability\IManageConfigValues;
37 use Friendica\Core\L10n;
38 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
39 use Friendica\Core\Renderer;
40 use Friendica\Core\Session\Capability\IHandleUserSessions;
41 use Friendica\Model\Contact;
42 use Friendica\Model\Post;
43 use Friendica\Model\User;
44 use Friendica\Module\Security\Login;
45 use Friendica\Network\HTTPException;
46 use Friendica\Core\Session\Model\UserSession;
47 use Friendica\Database\Database;
48 use Friendica\Model\Item;
49 use Friendica\Module\Response;
50 use Friendica\Navigation\SystemMessages;
51 use Friendica\Util\DateTimeFormat;
52 use Friendica\Util\Profiler;
53 use Psr\Log\LoggerInterface;
54
55 class Channel extends BaseModule
56 {
57         const WHATSHOT  = 'whatshot';
58         const FORYOU    = 'foryou';
59         const FOLLOWERS = 'followers';
60         const SHARERSOFSHARERS = 'sharersofsharers';
61         const IMAGE     = 'image';
62         const VIDEO     = 'video';
63         const AUDIO     = 'audio';
64         const LANGUAGE  = 'language';
65
66         protected static $content;
67         protected static $accountTypeString;
68         protected static $accountType;
69         protected static $itemsPerPage;
70         protected static $min_id;
71         protected static $max_id;
72         protected static $item_id;
73
74         /** @var UserSession */
75         protected $session;
76         /** @var ICanCache */
77         protected $cache;
78         /** @var IManageConfigValues The config */
79         protected $config;
80         /** @var SystemMessages */
81         protected $systemMessages;
82         /** @var App\Page */
83         protected $page;
84         /** @var Conversation */
85         protected $conversation;
86         /** @var App\Mode $mode */
87         protected $mode;
88         /** @var IManagePersonalConfigValues */
89         protected $pConfig;
90         /** @var Database */
91         protected $database;
92
93
94         public function __construct(SystemMessages $systemMessages, Database $database, IManagePersonalConfigValues $pConfig, Mode $mode, Conversation $conversation, App\Page $page, IManageConfigValues $config, ICanCache $cache, IHandleUserSessions $session, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
95         {
96                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
97
98                 $this->systemMessages = $systemMessages;
99                 $this->database       = $database;
100                 $this->pConfig        = $pConfig;
101                 $this->mode           = $mode;
102                 $this->conversation   = $conversation;
103                 $this->page           = $page;
104                 $this->config         = $config;
105                 $this->cache          = $cache;
106                 $this->session        = $session;
107         }
108
109         protected function content(array $request = []): string
110         {
111                 if (!$this->session->getLocalUserId()) {
112                         return Login::form();
113                 }
114
115                 $this->parseRequest($request);
116
117                 $t = Renderer::getMarkupTemplate("community.tpl");
118                 $o = Renderer::replaceMacros($t, [
119                         '$content' => '',
120                         '$header'  => '',
121                 ]);
122
123                 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
124                         $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
125                         $o .= Renderer::replaceMacros($tpl, ['$reload_uri' => $this->args->getQueryString()]);
126                 }
127
128                 if (empty($request['mode']) || ($request['mode'] != 'raw')) {
129                         $tabs = [];
130
131                         $tabs[] = [
132                                 'label'     => $this->l10n->t('For you'),
133                                 'url'       => 'channel/' . self::FORYOU,
134                                 'sel'       => self::$content == self::FORYOU ? 'active' : '',
135                                 'title'     => $this->l10n->t('Posts from contacts you interact with and who interact with you'),
136                                 'id'        => 'channel-foryou-tab',
137                                 'accesskey' => 'y'
138                         ];
139
140                         $tabs[] = [
141                                 'label'     => $this->l10n->t('What\'s Hot'),
142                                 'url'       => 'channel/' . self::WHATSHOT,
143                                 'sel'       => self::$content == self::WHATSHOT ? 'active' : '',
144                                 'title'     => $this->l10n->t('Posts with a lot of interactions'),
145                                 'id'        => 'channel-whatshot-tab',
146                                 'accesskey' => 'h'
147                         ];
148
149                         $language  = User::getLanguageCode($this->session->getLocalUserId());
150                         $languages = $this->l10n->getAvailableLanguages(true);
151
152                         $tabs[] = [
153                                 'label'     => $languages[$language],
154                                 'url'       => 'channel/' . self::LANGUAGE,
155                                 'sel'       => self::$content == self::LANGUAGE ? 'active' : '',
156                                 'title'     => $this->l10n->t('Posts in %s', $languages[$language]),
157                                 'id'        => 'channel-language-tab',
158                                 'accesskey' => 'g'
159                         ];
160
161                         $tabs[] = [
162                                 'label'     => $this->l10n->t('Followers'),
163                                 'url'       => 'channel/' . self::FOLLOWERS,
164                                 'sel'       => self::$content == self::FOLLOWERS ? 'active' : '',
165                                 'title'     => $this->l10n->t('Posts from your followers that you don\'t follow'),
166                                 'id'        => 'channel-followers-tab',
167                                 'accesskey' => 'f'
168                         ];
169
170                         $tabs[] = [
171                                 'label'     => $this->l10n->t('Sharers of sharers'),
172                                 'url'       => 'channel/' . self::SHARERSOFSHARERS,
173                                 'sel'       => self::$content == self::SHARERSOFSHARERS ? 'active' : '',
174                                 'title'     => $this->l10n->t('Posts from accounts that are followed by accounts that you follow'),
175                                 'id'        => 'channel-' . self::SHARERSOFSHARERS . '-tab',
176                                 'accesskey' => 'f'
177                         ];
178
179                         $tabs[] = [
180                                 'label'     => $this->l10n->t('Images'),
181                                 'url'       => 'channel/' . self::IMAGE,
182                                 'sel'       => self::$content == self::IMAGE ? 'active' : '',
183                                 'title'     => $this->l10n->t('Posts with images'),
184                                 'id'        => 'channel-image-tab',
185                                 'accesskey' => 'i'
186                         ];
187
188                         $tabs[] = [
189                                 'label'     => $this->l10n->t('Audio'),
190                                 'url'       => 'channel/' . self::AUDIO,
191                                 'sel'       => self::$content == self::AUDIO ? 'active' : '',
192                                 'title'     => $this->l10n->t('Posts with audio'),
193                                 'id'        => 'channel-audio-tab',
194                                 'accesskey' => 'd'
195                         ];
196
197                         $tabs[] = [
198                                 'label'     => $this->l10n->t('Videos'),
199                                 'url'       => 'channel/' . self::VIDEO,
200                                 'sel'       => self::$content == self::VIDEO ? 'active' : '',
201                                 'title'     => $this->l10n->t('Posts with videos'),
202                                 'id'        => 'channel-video-tab',
203                                 'accesskey' => 'v'
204                         ];
205
206                         $tab_tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
207                         $o .= Renderer::replaceMacros($tab_tpl, ['$tabs' => $tabs]);
208
209                         Nav::setSelected('channel');
210
211                         $this->page['aside'] .= Widget::accountTypes('channel/' . self::$content, self::$accountTypeString);
212
213                         if (!in_array(self::$content, [self::FOLLOWERS, self::FORYOU]) && $this->config->get('system', 'community_no_sharer')) {
214                                 $path = self::$content;
215                                 if (!empty($this->parameters['accounttype'])) {
216                                         $path .= '/' . $this->parameters['accounttype'];
217                                 }
218                                 $query_parameters = [];
219
220                                 if (!empty($request['min_id'])) {
221                                         $query_parameters['min_id'] = $request['min_id'];
222                                 }
223                                 if (!empty($request['max_id'])) {
224                                         $query_parameters['max_id'] = $request['max_id'];
225                                 }
226                                 if (!empty($request['last_created'])) {
227                                         $query_parameters['max_id'] = $request['last_created'];
228                                 }
229
230                                 $path_all       = $path . (!empty($query_parameters) ? '?' . http_build_query($query_parameters) : '');
231                                 $path_no_sharer = $path . '?' . http_build_query(array_merge($query_parameters, ['no_sharer' => true]));
232                                 $this->page['aside'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/community_sharer.tpl'), [
233                                         '$title'           => $this->l10n->t('Own Contacts'),
234                                         '$path_all'        => $path_all,
235                                         '$path_no_sharer'  => $path_no_sharer,
236                                         '$no_sharer'       => !empty($request['no_sharer']),
237                                         '$all'             => $this->l10n->t('Include'),
238                                         '$no_sharer_label' => $this->l10n->t('Hide'),
239                                         '$base'            => 'channel',
240                                 ]);
241                         }
242
243                         if (Feature::isEnabled($this->session->getLocalUserId(), 'trending_tags')) {
244                                 $this->page['aside'] .= TrendingTags::getHTML(self::$content);
245                         }
246
247                         // We need the editor here to be able to reshare an item.
248                         $o .= $this->conversation->statusEditor([], 0, true);
249                 }
250
251                 $items = $this->getItems($request);
252
253                 if (!$this->database->isResult($items)) {
254                         $this->systemMessages->addNotice($this->l10n->t('No results.'));
255                         return $o;
256                 }
257
258                 $o .= $this->conversation->render($items, Conversation::MODE_CHANNEL, false, false, 'created', $this->session->getLocalUserId());
259
260                 $pager = new BoundariesPager(
261                         $this->l10n,
262                         $this->args->getQueryString(),
263                         $items[0]['created'],
264                         $items[count($items) - 1]['created'],
265                         self::$itemsPerPage
266                 );
267
268                 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
269                         $o .= HTML::scrollLoader();
270                 } else {
271                         $o .= $pager->renderMinimal(count($items));
272                 }
273
274                 return $o;
275         }
276
277         /**
278          * Computes module parameters from the request and local configuration
279          *
280          * @throws HTTPException\BadRequestException
281          * @throws HTTPException\ForbiddenException
282          */
283         protected function parseRequest(array $request)
284         {
285                 self::$accountTypeString = $request['accounttype'] ?? $this->parameters['accounttype'] ?? '';
286                 self::$accountType       = User::getAccountTypeByString(self::$accountTypeString);
287
288                 self::$content = $this->parameters['content'] ?? '';
289                 if (!self::$content) {
290                         self::$content = self::FORYOU;
291                 }
292
293                 if (!in_array(self::$content, [self::WHATSHOT, self::FORYOU, self::FOLLOWERS, self::SHARERSOFSHARERS, self::IMAGE, self::VIDEO, self::AUDIO, self::LANGUAGE])) {
294                         throw new HTTPException\BadRequestException($this->l10n->t('Channel not available.'));
295                 }
296
297                 if ($this->mode->isMobile()) {
298                         self::$itemsPerPage = $this->pConfig->get(
299                                 $this->session->getLocalUserId(),
300                                 'system',
301                                 'itemspage_mobile_network',
302                                 $this->config->get('system', 'itemspage_network_mobile')
303                         );
304                 } else {
305                         self::$itemsPerPage = $this->pConfig->get(
306                                 $this->session->getLocalUserId(),
307                                 'system',
308                                 'itemspage_network',
309                                 $this->config->get('system', 'itemspage_network')
310                         );
311                 }
312
313                 if (!empty($request['item'])) {
314                         $item          = Post::selectFirst(['parent-uri-id'], ['id' => $request['item']]);
315                         self::$item_id = $item['parent-uri-id'] ?? 0;
316                 } else {
317                         self::$item_id = 0;
318                 }
319
320                 self::$min_id = $request['min_id']       ?? null;
321                 self::$max_id = $request['last_created'] ?? $request['max_id'] ?? null;
322         }
323
324         /**
325          * Computes the displayed items.
326          *
327          * Community pages have a restriction on how many successive posts by the same author can show on any given page,
328          * so we may have to retrieve more content beyond the first query
329          *
330          * @return array
331          * @throws \Exception
332          */
333         protected function getItems(array $request)
334         {
335                 if (self::$content == self::WHATSHOT) {
336                         if (!is_null(self::$accountType)) {
337                                 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` = ?", $this->getMedianComments(4), $this->getMedianActivities(4), self::$accountType];
338                         } else {
339                                 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` != ?", $this->getMedianComments(4), $this->getMedianActivities(4), Contact::TYPE_COMMUNITY];
340                         }
341                 } elseif (self::$content == self::FORYOU) {
342                         $cid = Contact::getPublicIdByUserId($this->session->getLocalUserId());
343
344                         $condition = [
345                                 "(`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `relation-thread-score` > ?) OR
346                                 ((`comments` >= ? OR `activities` >= ?) AND `owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ?)) OR
347                                 (`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` IN (?, ?) AND `notify_new_posts`)))",
348                                 $cid, $this->getMedianRelationThreadScore($cid, 4), $this->getMedianComments(4), $this->getMedianActivities(4), $cid,
349                                 $this->session->getLocalUserId(), Contact::FRIEND, Contact::SHARING
350                         ];
351                 } elseif (self::$content == self::FOLLOWERS) {
352                         $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` = ?)", $this->session->getLocalUserId(), Contact::FOLLOWER];
353                 } elseif (self::$content == self::SHARERSOFSHARERS) {
354                         $cid = Contact::getPublicIdByUserId($this->session->getLocalUserId());
355
356                         $condition = [
357                                 "`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `last-interaction` > ?
358                                 AND `relation-cid` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ? AND `relation-thread-score` >= ?)
359                                 AND NOT `cid` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ?))",
360                                 DateTimeFormat::utc('now - 90 day'), $cid, $this->getMedianRelationThreadScore($cid, 4), $cid
361                         ];
362                 } elseif (self::$content == self::IMAGE) {
363                         $condition = ["`media-type` & ?", 1];
364                 } elseif (self::$content == self::VIDEO) {
365                         $condition = ["`media-type` & ?", 2];
366                 } elseif (self::$content == self::AUDIO) {
367                         $condition = ["`media-type` & ?", 4];
368                 } elseif (self::$content == self::LANGUAGE) {
369                         $condition = ["JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?", $this->l10n->convertCodeForLanguageDetection(User::getLanguageCode($this->session->getLocalUserId()))];
370                 }
371
372                 if (self::$content != self::LANGUAGE) {
373                         $condition = $this->addLanguageCondition($condition);
374                 }
375
376                 $condition[0] .= " AND NOT EXISTS(SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `post-engagement`.`owner-id` AND (`ignored` OR `blocked` OR `collapsed`))";
377                 $condition[] = $this->session->getLocalUserId();
378
379                 if ((self::$content != self::WHATSHOT) && !is_null(self::$accountType)) {
380                         $condition[0] .= " AND `contact-type` = ?";
381                         $condition[] = self::$accountType;
382                 }
383
384                 $params = ['order' => ['created' => true], 'limit' => self::$itemsPerPage];
385
386                 if (!empty(self::$item_id)) {
387                         $condition[0] .= " AND `uri-id` = ?";
388                         $condition[] = self::$item_id;
389                 } else {
390                         if (!empty($request['no_sharer'])) {
391                                 $condition[0] .= " AND NOT `uri-id` IN (SELECT `uri-id` FROM `post-user` WHERE `post-user`.`uid` = ? AND `post-user`.`uri-id` = `post-engagement`.`uri-id`)";
392                                 $condition[] = $this->session->getLocalUserId();
393                         }
394
395                         if (isset(self::$max_id)) {
396                                 $condition[0] .= " AND `created` < ?";
397                                 $condition[] = self::$max_id;
398                         }
399
400                         if (isset(self::$min_id)) {
401                                 $condition[0] .= " AND `created` > ?";
402                                 $condition[] = self::$min_id;
403
404                                 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
405                                 if (!isset(self::$max_id)) {
406                                         $params['order']['created'] = false;
407                                 }
408                         }
409                 }
410
411                 $items = $this->database->selectToArray('post-engagement', ['uri-id', 'created'], $condition, $params);
412                 if (empty($items)) {
413                         return [];
414                 }
415
416                 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
417                 if (empty(self::$item_id) && isset(self::$min_id) && !isset(self::$max_id)) {
418                         $items = array_reverse($items);
419                 }
420
421                 Item::update(['unseen' => false], ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'uri-id' => array_column($items, 'uri-id')]);
422
423                 return $items;
424         }
425
426         private function addLanguageCondition(array $condition): array
427         {
428                 $conditions = [];
429                 $languages  = $this->pConfig->get($this->session->getLocalUserId(), 'channel', 'languages', [User::getLanguageCode($this->session->getLocalUserId())]);
430                 $languages  = $this->l10n->convertForLanguageDetection($languages);
431                 foreach ($languages as $language) {
432                         $conditions[] = "JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?";
433                         $condition[]  = $language;
434                 }
435                 if (!empty($conditions)) {
436                         $condition[0] .= " AND (`language` IS NULL OR " . implode(' OR ', $conditions) . ")";
437                 }
438                 return $condition;
439         }
440
441         private function getMedianComments(int $divider): int
442         {
443                 $cache_key = 'Channel:getMedianComments:' . $divider;
444                 $comments  = $this->cache->get($cache_key);
445                 if (!empty($comments)) {
446                         return $comments;
447                 }
448
449                 $limit    = $this->database->count('post-engagement', ["`contact-type` != ? AND `comments` > ?", Contact::TYPE_COMMUNITY, 0]) / $divider;
450                 $post     = $this->database->selectToArray('post-engagement', ['comments'], ["`contact-type` != ?", Contact::TYPE_COMMUNITY], ['order' => ['comments' => true], 'limit' => [$limit, 1]]);
451                 $comments = $post[0]['comments'] ?? 0;
452                 if (empty($comments)) {
453                         return 0;
454                 }
455
456                 $this->cache->set($cache_key, $comments, Duration::HOUR);
457                 return $comments;
458         }
459
460         private function getMedianActivities(int $divider): int
461         {
462                 $cache_key  = 'Channel:getMedianActivities:' . $divider;
463                 $activities = $this->cache->get($cache_key);
464                 if (!empty($activities)) {
465                         return $activities;
466                 }
467
468                 $limit      = $this->database->count('post-engagement', ["`contact-type` != ? AND `activities` > ?", Contact::TYPE_COMMUNITY, 0]) / $divider;
469                 $post       = $this->database->selectToArray('post-engagement', ['activities'], ["`contact-type` != ?", Contact::TYPE_COMMUNITY], ['order' => ['activities' => true], 'limit' => [$limit, 1]]);
470                 $activities = $post[0]['activities'] ?? 0;
471                 if (empty($activities)) {
472                         return 0;
473                 }
474
475                 $this->cache->set($cache_key, $activities, Duration::HOUR);
476                 return $activities;
477         }
478
479         private function getMedianRelationThreadScore(int $cid, int $divider): int
480         {
481                 $cache_key = 'Channel:getThreadScore:' . $cid . ':' . $divider;
482                 $score     = $this->cache->get($cache_key);
483                 if (!empty($score)) {
484                         return $score;
485                 }
486
487                 $limit    = $this->database->count('contact-relation', ["`relation-cid` = ? AND `relation-thread-score` > ?", $cid, 0]) / $divider;
488                 $relation = $this->database->selectToArray('contact-relation', ['relation-thread-score'], ['relation-cid' => $cid], ['order' => ['relation-thread-score' => true], 'limit' => [$limit, 1]]);
489                 $score    = $relation[0]['relation-thread-score'] ?? 0;
490                 if (empty($score)) {
491                         return 0;
492                 }
493
494                 $this->cache->set($cache_key, $score, Duration::HOUR);
495                 return $score;
496         }
497 }