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