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