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