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\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\Profiler;
52 use Psr\Log\LoggerInterface;
54 class Channel extends BaseModule
56 const WHATSHOT = 'whatshot';
57 const FORYOU = 'foryou';
58 const FOLLOWERS = 'followers';
59 const IMAGE = 'image';
60 const VIDEO = 'video';
61 const AUDIO = 'audio';
62 const LANGUAGE = 'language';
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;
72 /** @var UserSession */
76 /** @var IManageConfigValues The config */
78 /** @var SystemMessages */
79 protected $systemMessages;
82 /** @var Conversation */
83 protected $conversation;
84 /** @var App\Mode $mode */
86 /** @var IManagePersonalConfigValues */
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 = [])
94 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
96 $this->systemMessages = $systemMessages;
97 $this->database = $database;
98 $this->pConfig = $pConfig;
100 $this->conversation = $conversation;
102 $this->config = $config;
103 $this->cache = $cache;
104 $this->session = $session;
107 protected function content(array $request = []): string
109 if (!$this->session->getLocalUserId()) {
110 return Login::form();
113 $this->parseRequest($request);
115 $t = Renderer::getMarkupTemplate("community.tpl");
116 $o = Renderer::replaceMacros($t, [
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()]);
126 if (empty($request['mode']) || ($request['mode'] != 'raw')) {
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',
139 'label' => $this->l10n->t('What\'s Hot'),
140 'url' => 'channel/' . self::WHATSHOT,
141 'sel' => self::$content == self::WHATSHOT ? 'active' : '',
142 'title' => $this->l10n->t('Posts with a lot of interactions'),
143 'id' => 'channel-whatshot-tab',
147 $language = User::getLanguageCode($this->session->getLocalUserId());
148 $languages = $this->l10n->getAvailableLanguages(true);
151 'label' => $languages[$language],
152 'url' => 'channel/' . self::LANGUAGE,
153 'sel' => self::$content == self::LANGUAGE ? 'active' : '',
154 'title' => $this->l10n->t('Posts in %s', $languages[$language]),
155 'id' => 'channel-language-tab',
160 'label' => $this->l10n->t('Followers'),
161 'url' => 'channel/' . self::FOLLOWERS,
162 'sel' => self::$content == self::FOLLOWERS ? 'active' : '',
163 'title' => $this->l10n->t('Posts from your followers that you don\'t follow'),
164 'id' => 'channel-followers-tab',
169 'label' => $this->l10n->t('Images'),
170 'url' => 'channel/' . self::IMAGE,
171 'sel' => self::$content == self::IMAGE ? 'active' : '',
172 'title' => $this->l10n->t('Posts with images'),
173 'id' => 'channel-image-tab',
178 'label' => $this->l10n->t('Audio'),
179 'url' => 'channel/' . self::AUDIO,
180 'sel' => self::$content == self::AUDIO ? 'active' : '',
181 'title' => $this->l10n->t('Posts with audio'),
182 'id' => 'channel-audio-tab',
187 'label' => $this->l10n->t('Videos'),
188 'url' => 'channel/' . self::VIDEO,
189 'sel' => self::$content == self::VIDEO ? 'active' : '',
190 'title' => $this->l10n->t('Posts with videos'),
191 'id' => 'channel-video-tab',
195 $tab_tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
196 $o .= Renderer::replaceMacros($tab_tpl, ['$tabs' => $tabs]);
198 Nav::setSelected('channel');
200 $this->page['aside'] .= Widget::accountTypes('channel/' . self::$content, self::$accountTypeString);
202 if (!in_array(self::$content, [self::FOLLOWERS, self::FORYOU]) && $this->config->get('system', 'community_no_sharer')) {
203 $path = self::$content;
204 if (!empty($this->parameters['accounttype'])) {
205 $path .= '/' . $this->parameters['accounttype'];
207 $query_parameters = [];
209 if (!empty($request['min_id'])) {
210 $query_parameters['min_id'] = $request['min_id'];
212 if (!empty($request['max_id'])) {
213 $query_parameters['max_id'] = $request['max_id'];
215 if (!empty($request['last_created'])) {
216 $query_parameters['max_id'] = $request['last_created'];
219 $path_all = $path . (!empty($query_parameters) ? '?' . http_build_query($query_parameters) : '');
220 $path_no_sharer = $path . '?' . http_build_query(array_merge($query_parameters, ['no_sharer' => true]));
221 $this->page['aside'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/community_sharer.tpl'), [
222 '$title' => $this->l10n->t('Own Contacts'),
223 '$path_all' => $path_all,
224 '$path_no_sharer' => $path_no_sharer,
225 '$no_sharer' => !empty($request['no_sharer']),
226 '$all' => $this->l10n->t('Include'),
227 '$no_sharer_label' => $this->l10n->t('Hide'),
228 '$base' => 'channel',
232 if (Feature::isEnabled($this->session->getLocalUserId(), 'trending_tags')) {
233 $this->page['aside'] .= TrendingTags::getHTML(self::$content);
236 // We need the editor here to be able to reshare an item.
237 $o .= $this->conversation->statusEditor([], 0, true);
240 $items = $this->getItems($request);
242 if (!$this->database->isResult($items)) {
243 $this->systemMessages->addNotice($this->l10n->t('No results.'));
247 $o .= $this->conversation->render($items, Conversation::MODE_CHANNEL, false, false, 'created', $this->session->getLocalUserId());
249 $pager = new BoundariesPager(
251 $this->args->getQueryString(),
252 $items[0]['created'],
253 $items[count($items) - 1]['created'],
257 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
258 $o .= HTML::scrollLoader();
260 $o .= $pager->renderMinimal(count($items));
267 * Computes module parameters from the request and local configuration
269 * @throws HTTPException\BadRequestException
270 * @throws HTTPException\ForbiddenException
272 protected function parseRequest(array $request)
274 self::$accountTypeString = $request['accounttype'] ?? $this->parameters['accounttype'] ?? '';
275 self::$accountType = User::getAccountTypeByString(self::$accountTypeString);
277 self::$content = $this->parameters['content'] ?? '';
278 if (!self::$content) {
279 self::$content = self::FORYOU;
282 if (!in_array(self::$content, [self::WHATSHOT, self::FORYOU, self::FOLLOWERS, self::IMAGE, self::VIDEO, self::AUDIO, self::LANGUAGE])) {
283 throw new HTTPException\BadRequestException($this->l10n->t('Channel not available.'));
286 if ($this->mode->isMobile()) {
287 self::$itemsPerPage = $this->pConfig->get(
288 $this->session->getLocalUserId(),
290 'itemspage_mobile_network',
291 $this->config->get('system', 'itemspage_network_mobile')
294 self::$itemsPerPage = $this->pConfig->get(
295 $this->session->getLocalUserId(),
298 $this->config->get('system', 'itemspage_network')
302 if (!empty($request['item'])) {
303 $item = Post::selectFirst(['parent-uri-id'], ['id' => $request['item']]);
304 self::$item_id = $item['parent-uri-id'] ?? 0;
309 self::$min_id = $request['min_id'] ?? null;
310 self::$max_id = $request['last_created'] ?? $request['max_id'] ?? null;
314 * Computes the displayed items.
316 * Community pages have a restriction on how many successive posts by the same author can show on any given page,
317 * so we may have to retrieve more content beyond the first query
322 protected function getItems(array $request)
324 if (self::$content == self::WHATSHOT) {
325 if (!is_null(self::$accountType)) {
326 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` = ?", $this->getMedianComments(4), $this->getMedianActivities(4), self::$accountType];
328 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` != ?", $this->getMedianComments(4), $this->getMedianActivities(4), Contact::TYPE_COMMUNITY];
330 } elseif (self::$content == self::FORYOU) {
331 $cid = Contact::getPublicIdByUserId($this->session->getLocalUserId());
333 $condition = ["(`owner-id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `thread-score` > ?) OR
334 ((`comments` >= ? OR `activities` >= ?) AND `owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` IN (?, ?))) OR
335 ( `owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` IN (?, ?) AND `notify_new_posts`)))",
336 $cid, $this->getMedianThreadScore($cid, 4), $this->getMedianComments(4), $this->getMedianActivities(4), $this->session->getLocalUserId(), Contact::FRIEND, Contact::SHARING,
337 $this->session->getLocalUserId(), Contact::FRIEND, Contact::SHARING];
338 } elseif (self::$content == self::FOLLOWERS) {
339 $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` = ?)", $this->session->getLocalUserId(), Contact::FOLLOWER];
340 } elseif (self::$content == self::IMAGE) {
341 $condition = ["`media-type` & ?", 1];
342 } elseif (self::$content == self::VIDEO) {
343 $condition = ["`media-type` & ?", 2];
344 } elseif (self::$content == self::AUDIO) {
345 $condition = ["`media-type` & ?", 4];
346 } elseif (self::$content == self::LANGUAGE) {
347 $condition = ["JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?", $this->l10n->convertCodeForLanguageDetection(User::getLanguageCode($this->session->getLocalUserId()))];
350 if (self::$content != self::LANGUAGE) {
351 $condition = $this->addLanguageCondition($condition);
354 $condition[0] .= " AND NOT EXISTS(SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `post-engagement`.`owner-id` AND (`ignored` OR `blocked` OR `collapsed`))";
355 $condition[] = $this->session->getLocalUserId();
357 if ((self::$content != self::WHATSHOT) && !is_null(self::$accountType)) {
358 $condition[0] .= " AND `contact-type` = ?";
359 $condition[] = self::$accountType;
362 $params = ['order' => ['created' => true], 'limit' => self::$itemsPerPage];
364 if (!empty(self::$item_id)) {
365 $condition[0] .= " AND `uri-id` = ?";
366 $condition[] = self::$item_id;
368 if (!empty($request['no_sharer'])) {
369 $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`)";
370 $condition[] = $this->session->getLocalUserId();
373 if (isset(self::$max_id)) {
374 $condition[0] .= " AND `created` < ?";
375 $condition[] = self::$max_id;
378 if (isset(self::$min_id)) {
379 $condition[0] .= " AND `created` > ?";
380 $condition[] = self::$min_id;
382 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
383 if (!isset(self::$max_id)) {
384 $params['order']['created'] = false;
389 $items = $this->database->selectToArray('post-engagement', ['uri-id', 'created'], $condition, $params);
394 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
395 if (empty(self::$item_id) && isset(self::$min_id) && !isset(self::$max_id)) {
396 $items = array_reverse($items);
399 Item::update(['unseen' => false], ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'uri-id' => array_column($items, 'uri-id')]);
404 private function addLanguageCondition(array $condition): array
407 $languages = $this->pConfig->get($this->session->getLocalUserId(), 'channel', 'languages', [User::getLanguageCode($this->session->getLocalUserId())]);
408 $languages = $this->l10n->convertForLanguageDetection($languages);
409 foreach ($languages as $language) {
410 $conditions[] = "JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?";
411 $condition[] = $language;
413 if (!empty($conditions)) {
414 $condition[0] .= " AND (`language` IS NULL OR " . implode(' OR ', $conditions) . ")";
419 private function getMedianComments(int $divider): int
421 $cache_key = 'Channel:getMedianComments:' . $divider;
422 $comments = $this->cache->get($cache_key);
423 if (!empty($comments)) {
427 $limit = $this->database->count('post-engagement', ["`contact-type` != ? AND `comments` > ?", Contact::TYPE_COMMUNITY, 0]) / $divider;
428 $post = $this->database->selectToArray('post-engagement', ['comments'], ["`contact-type` != ?", Contact::TYPE_COMMUNITY], ['order' => ['comments' => true], 'limit' => [$limit, 1]]);
429 $comments = $post[0]['comments'] ?? 0;
430 if (empty($comments)) {
434 $this->cache->set($cache_key, $comments, Duration::HOUR);
438 private function getMedianActivities(int $divider): int
440 $cache_key = 'Channel:getMedianActivities:' . $divider;
441 $activities = $this->cache->get($cache_key);
442 if (!empty($activities)) {
446 $limit = $this->database->count('post-engagement', ["`contact-type` != ? AND `activities` > ?", Contact::TYPE_COMMUNITY, 0]) / $divider;
447 $post = $this->database->selectToArray('post-engagement', ['activities'], ["`contact-type` != ?", Contact::TYPE_COMMUNITY], ['order' => ['activities' => true], 'limit' => [$limit, 1]]);
448 $activities = $post[0]['activities'] ?? 0;
449 if (empty($activities)) {
453 $this->cache->set($cache_key, $activities, Duration::HOUR);
457 private function getMedianThreadScore(int $cid, int $divider): int
459 $cache_key = 'Channel:getThreadScore:' . $cid . ':' . $divider;
460 $score = $this->cache->get($cache_key);
461 if (!empty($score)) {
465 $limit = $this->database->count('contact-relation', ["`cid` = ? AND `thread-score` > ?", $cid, 0]) / $divider;
466 $relation = $this->database->selectToArray('contact-relation', ['thread-score'], ['cid' => $cid], ['order' => ['thread-score' => true], 'limit' => [$limit, 1]]);
467 $score = $relation[0]['thread-score'] ?? 0;
472 $this->cache->set($cache_key, $score, Duration::HOUR);