3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Module\Conversation;
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;
52 class Channel extends BaseModule
54 const WHATSHOT = 'whatshot';
55 const FORYOU = 'foryou';
56 const FOLLOWERS = 'followers';
57 const IMAGE = 'image';
58 const VIDEO = 'video';
59 const AUDIO = 'audio';
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;
69 /** @var UserSession */
73 /** @var IManageConfigValues The config */
75 /** @var SystemMessages */
76 private $systemMessages;
79 /** @var Conversation */
80 private $conversation;
81 /** @var App\Mode $mode */
83 /** @var IManagePersonalConfigValues */
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 = [])
88 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
90 $this->pConfig = $pConfig;
92 $this->conversation = $conversation;
94 $this->config = $config;
95 $this->cache = $cache;
96 $this->session = $session;
99 protected function content(array $request = []): string
101 if (!$this->session->getLocalUserId()) {
102 return Login::form();
105 $this->parseRequest($request);
107 $t = Renderer::getMarkupTemplate("community.tpl");
108 $o = Renderer::replaceMacros($t, [
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()]);
118 if (empty($request['mode']) || ($request['mode'] != 'raw')) {
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',
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',
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',
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',
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',
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',
175 $tab_tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
176 $o .= Renderer::replaceMacros($tab_tpl, ['$tabs' => $tabs]);
178 Nav::setSelected('channel');
180 $this->page['aside'] .= Widget::accountTypes('channel/' . self::$content, self::$accountTypeString);
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'];
187 $query_parameters = [];
189 if (!empty($request['min_id'])) {
190 $query_parameters['min_id'] = $request['min_id'];
192 if (!empty($request['max_id'])) {
193 $query_parameters['max_id'] = $request['max_id'];
195 if (!empty($request['last_created'])) {
196 $query_parameters['max_id'] = $request['last_created'];
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',
212 if (Feature::isEnabled($this->session->getLocalUserId(), 'trending_tags')) {
213 $this->page['aside'] .= TrendingTags::getHTML(self::$content);
216 // We need the editor here to be able to reshare an item.
217 $o .= $this->conversation->statusEditor([], 0, true);
220 $items = $this->getItems($request, $this->session, $this->cache);
222 if (!DBA::isResult($items)) {
223 $this->systemMessages->addNotice($this->l10n->t('No results.'));
227 $o .= $this->conversation->render($items, Conversation::MODE_CHANNEL, false, false, 'created', $this->session->getLocalUserId());
229 $pager = new BoundariesPager(
231 $this->args->getQueryString(),
232 $items[0]['created'],
233 $items[count($items) - 1]['created'],
237 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
238 $o .= HTML::scrollLoader();
240 $o .= $pager->renderMinimal(count($items));
247 * Computes module parameters from the request and local configuration
249 * @throws HTTPException\BadRequestException
250 * @throws HTTPException\ForbiddenException
252 protected function parseRequest(array $request)
254 self::$accountTypeString = $request['accounttype'] ?? $this->parameters['accounttype'] ?? '';
255 self::$accountType = User::getAccountTypeByString(self::$accountTypeString);
257 self::$content = $this->parameters['content'] ?? '';
258 if (!self::$content) {
259 self::$content = self::FORYOU;
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.'));
266 if ($this->mode->isMobile()) {
267 self::$itemsPerPage = $this->pConfig->get(
268 $this->session->getLocalUserId(),
270 'itemspage_mobile_network',
271 $this->config->get('system', 'itemspage_network_mobile')
274 self::$itemsPerPage = $this->pConfig->get(
275 $this->session->getLocalUserId(),
278 $this->config->get('system', 'itemspage_network')
282 if (!empty($request['item'])) {
283 $item = Post::selectFirst(['parent-uri-id'], ['id' => $request['item']]);
284 self::$item_id = $item['parent-uri-id'] ?? 0;
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;
295 * Computes the displayed items.
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
303 protected function getItems(array $request, UserSession $session, ICanCache $cache)
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];
309 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` != ?", $this->getMedianComments(4), $this->getMedianActivities(4), Contact::TYPE_COMMUNITY];
311 } elseif (self::$content == self::FORYOU) {
312 $cid = Contact::getPublicIdByUserId($session->getLocalUserId());
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];
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();
332 if ((self::$content != self::WHATSHOT) && !is_null(self::$accountType)) {
333 $condition[0] .= " AND `contact-type` = ?";
334 $condition[] = self::$accountType;
337 $params = ['order' => ['created' => true], 'limit' => self::$itemsPerPage];
339 if (!empty(self::$item_id)) {
340 $condition[0] .= " AND `uri-id` = ?";
341 $condition[] = self::$item_id;
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();
348 if (isset(self::$max_id)) {
349 $condition[0] .= " AND `created` < ?";
350 $condition[] = self::$max_id;
353 if (isset(self::$min_id)) {
354 $condition[0] .= " AND `created` > ?";
355 $condition[] = self::$min_id;
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;
364 $items = DBA::selectToArray('post-engagement', ['uri-id', 'created'], $condition, $params);
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);
378 private function getMedianComments(int $divider): int
380 $cache_key = 'Channel:getMedianComments:' . $divider;
381 $comments = $this->cache->get($cache_key);
382 if (!empty($comments)) {
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)) {
393 $this->cache->set($cache_key, $comments, Duration::HOUR);
397 private function getMedianActivities(int $divider): int
399 $cache_key = 'Channel:getMedianActivities:' . $divider;
400 $activities = $this->cache->get($cache_key);
401 if (!empty($activities)) {
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)) {
412 $this->cache->set($cache_key, $activities, Duration::HOUR);
416 private function getMedianThreadScore(int $cid, int $divider): int
418 $cache_key = 'Channel:getThreadScore:' . $cid . ':' . $divider;
419 $score = $this->cache->get($cache_key);
420 if (!empty($score)) {
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;
431 $this->cache->set($cache_key, $score, Duration::HOUR);