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\Channel as ChannelModel;
49 use Friendica\Model\Item;
50 use Friendica\Module\Response;
51 use Friendica\Navigation\SystemMessages;
52 use Friendica\Util\Profiler;
53 use Psr\Log\LoggerInterface;
55 class Channel extends BaseModule
57 protected static $content;
58 protected static $accountTypeString;
59 protected static $accountType;
60 protected static $itemsPerPage;
61 protected static $min_id;
62 protected static $max_id;
63 protected static $item_id;
65 /** @var UserSession */
69 /** @var IManageConfigValues The config */
71 /** @var SystemMessages */
72 protected $systemMessages;
75 /** @var Conversation */
76 protected $conversation;
77 /** @var App\Mode $mode */
79 /** @var IManagePersonalConfigValues */
83 /** @var ChannelModel */
87 public function __construct(ChannelModel $channel, 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 = [])
89 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
91 $this->channel = $channel;
92 $this->systemMessages = $systemMessages;
93 $this->database = $database;
94 $this->pConfig = $pConfig;
96 $this->conversation = $conversation;
98 $this->config = $config;
99 $this->cache = $cache;
100 $this->session = $session;
103 protected function content(array $request = []): string
105 if (!$this->session->getLocalUserId()) {
106 return Login::form();
109 $this->parseRequest($request);
111 $t = Renderer::getMarkupTemplate("community.tpl");
112 $o = Renderer::replaceMacros($t, [
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()]);
122 if (empty($request['mode']) || ($request['mode'] != 'raw')) {
125 foreach ($this->channel->getForUser($this->session->getLocalUserId()) as $tab) {
127 'label' => $tab->label,
128 'url' => 'channel/' . $tab->code,
129 'sel' => self::$content == $tab->code ? 'active' : '',
130 'title' => $tab->description,
131 'id' => 'channel-' . $tab->code . '-tab',
132 'accesskey' => $tab->accessKey,
136 $tab_tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
137 $o .= Renderer::replaceMacros($tab_tpl, ['$tabs' => $tabs]);
139 Nav::setSelected('channel');
141 $this->page['aside'] .= Widget::accountTypes('channel/' . self::$content, self::$accountTypeString);
143 if (!in_array(self::$content, [ChannelModel::FOLLOWERS, ChannelModel::FORYOU]) && $this->config->get('system', 'community_no_sharer')) {
144 $path = self::$content;
145 if (!empty($this->parameters['accounttype'])) {
146 $path .= '/' . $this->parameters['accounttype'];
148 $query_parameters = [];
150 if (!empty($request['min_id'])) {
151 $query_parameters['min_id'] = $request['min_id'];
153 if (!empty($request['max_id'])) {
154 $query_parameters['max_id'] = $request['max_id'];
156 if (!empty($request['last_created'])) {
157 $query_parameters['max_id'] = $request['last_created'];
160 $path_all = $path . (!empty($query_parameters) ? '?' . http_build_query($query_parameters) : '');
161 $path_no_sharer = $path . '?' . http_build_query(array_merge($query_parameters, ['no_sharer' => true]));
162 $this->page['aside'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/community_sharer.tpl'), [
163 '$title' => $this->l10n->t('Own Contacts'),
164 '$path_all' => $path_all,
165 '$path_no_sharer' => $path_no_sharer,
166 '$no_sharer' => !empty($request['no_sharer']),
167 '$all' => $this->l10n->t('Include'),
168 '$no_sharer_label' => $this->l10n->t('Hide'),
169 '$base' => 'channel',
173 if (Feature::isEnabled($this->session->getLocalUserId(), 'trending_tags')) {
174 $this->page['aside'] .= TrendingTags::getHTML(self::$content);
177 // We need the editor here to be able to reshare an item.
178 $o .= $this->conversation->statusEditor([], 0, true);
181 $items = $this->getItems($request);
183 if (!$this->database->isResult($items)) {
184 $this->systemMessages->addNotice($this->l10n->t('No results.'));
188 $o .= $this->conversation->render($items, Conversation::MODE_CHANNEL, false, false, 'created', $this->session->getLocalUserId());
190 $pager = new BoundariesPager(
192 $this->args->getQueryString(),
193 $items[0]['created'],
194 $items[count($items) - 1]['created'],
198 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
199 $o .= HTML::scrollLoader();
201 $o .= $pager->renderMinimal(count($items));
208 * Computes module parameters from the request and local configuration
210 * @throws HTTPException\BadRequestException
211 * @throws HTTPException\ForbiddenException
213 protected function parseRequest(array $request)
215 self::$accountTypeString = $request['accounttype'] ?? $this->parameters['accounttype'] ?? '';
216 self::$accountType = User::getAccountTypeByString(self::$accountTypeString);
218 self::$content = $this->parameters['content'] ?? '';
219 if (!self::$content) {
220 self::$content = ChannelModel::FORYOU;
223 if (!in_array(self::$content, [ChannelModel::WHATSHOT, ChannelModel::FORYOU, ChannelModel::FOLLOWERS, ChannelModel::IMAGE, ChannelModel::VIDEO, ChannelModel::AUDIO, ChannelModel::LANGUAGE])) {
224 throw new HTTPException\BadRequestException($this->l10n->t('Channel not available.'));
227 if ($this->mode->isMobile()) {
228 self::$itemsPerPage = $this->pConfig->get(
229 $this->session->getLocalUserId(),
231 'itemspage_mobile_network',
232 $this->config->get('system', 'itemspage_network_mobile')
235 self::$itemsPerPage = $this->pConfig->get(
236 $this->session->getLocalUserId(),
239 $this->config->get('system', 'itemspage_network')
243 if (!empty($request['item'])) {
244 $item = Post::selectFirst(['parent-uri-id'], ['id' => $request['item']]);
245 self::$item_id = $item['parent-uri-id'] ?? 0;
250 self::$min_id = $request['min_id'] ?? null;
251 self::$max_id = $request['last_created'] ?? $request['max_id'] ?? null;
255 * Computes the displayed items.
257 * Community pages have a restriction on how many successive posts by the same author can show on any given page,
258 * so we may have to retrieve more content beyond the first query
263 protected function getItems(array $request)
265 if (self::$content == ChannelModel::WHATSHOT) {
266 if (!is_null(self::$accountType)) {
267 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` = ?", $this->getMedianComments(4), $this->getMedianActivities(4), self::$accountType];
269 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` != ?", $this->getMedianComments(4), $this->getMedianActivities(4), Contact::TYPE_COMMUNITY];
271 } elseif (self::$content == ChannelModel::FORYOU) {
272 $cid = Contact::getPublicIdByUserId($this->session->getLocalUserId());
274 $condition = ["(`owner-id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `thread-score` > ?) OR
275 ((`comments` >= ? OR `activities` >= ?) AND `owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` IN (?, ?))) OR
276 ( `owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` IN (?, ?) AND `notify_new_posts`)))",
277 $cid, $this->getMedianThreadScore($cid, 4), $this->getMedianComments(4), $this->getMedianActivities(4), $this->session->getLocalUserId(), Contact::FRIEND, Contact::SHARING,
278 $this->session->getLocalUserId(), Contact::FRIEND, Contact::SHARING];
279 } elseif (self::$content == ChannelModel::FOLLOWERS) {
280 $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` = ?)", $this->session->getLocalUserId(), Contact::FOLLOWER];
281 } elseif (self::$content == ChannelModel::IMAGE) {
282 $condition = ["`media-type` & ?", 1];
283 } elseif (self::$content == ChannelModel::VIDEO) {
284 $condition = ["`media-type` & ?", 2];
285 } elseif (self::$content == ChannelModel::AUDIO) {
286 $condition = ["`media-type` & ?", 4];
287 } elseif (self::$content == ChannelModel::LANGUAGE) {
288 $condition = ["JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?", $this->l10n->convertCodeForLanguageDetection(User::getLanguageCode($this->session->getLocalUserId()))];
291 if (self::$content != ChannelModel::LANGUAGE) {
292 $condition = $this->addLanguageCondition($condition);
295 $condition[0] .= " AND NOT EXISTS(SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `post-engagement`.`owner-id` AND (`ignored` OR `blocked` OR `collapsed`))";
296 $condition[] = $this->session->getLocalUserId();
298 if ((self::$content != ChannelModel::WHATSHOT) && !is_null(self::$accountType)) {
299 $condition[0] .= " AND `contact-type` = ?";
300 $condition[] = self::$accountType;
303 $params = ['order' => ['created' => true], 'limit' => self::$itemsPerPage];
305 if (!empty(self::$item_id)) {
306 $condition[0] .= " AND `uri-id` = ?";
307 $condition[] = self::$item_id;
309 if (!empty($request['no_sharer'])) {
310 $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`)";
311 $condition[] = $this->session->getLocalUserId();
314 if (isset(self::$max_id)) {
315 $condition[0] .= " AND `created` < ?";
316 $condition[] = self::$max_id;
319 if (isset(self::$min_id)) {
320 $condition[0] .= " AND `created` > ?";
321 $condition[] = self::$min_id;
323 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
324 if (!isset(self::$max_id)) {
325 $params['order']['created'] = false;
330 $items = $this->database->selectToArray('post-engagement', ['uri-id', 'created'], $condition, $params);
335 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
336 if (empty(self::$item_id) && isset(self::$min_id) && !isset(self::$max_id)) {
337 $items = array_reverse($items);
340 Item::update(['unseen' => false], ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'uri-id' => array_column($items, 'uri-id')]);
345 private function addLanguageCondition(array $condition): array
348 $languages = $this->pConfig->get($this->session->getLocalUserId(), 'channel', 'languages', [User::getLanguageCode($this->session->getLocalUserId())]);
349 $languages = $this->l10n->convertForLanguageDetection($languages);
350 foreach ($languages as $language) {
351 $conditions[] = "JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?";
352 $condition[] = $language;
354 if (!empty($conditions)) {
355 $condition[0] .= " AND (`language` IS NULL OR " . implode(' OR ', $conditions) . ")";
360 private function getMedianComments(int $divider): int
362 $cache_key = 'Channel:getMedianComments:' . $divider;
363 $comments = $this->cache->get($cache_key);
364 if (!empty($comments)) {
368 $limit = $this->database->count('post-engagement', ["`contact-type` != ? AND `comments` > ?", Contact::TYPE_COMMUNITY, 0]) / $divider;
369 $post = $this->database->selectToArray('post-engagement', ['comments'], ["`contact-type` != ?", Contact::TYPE_COMMUNITY], ['order' => ['comments' => true], 'limit' => [$limit, 1]]);
370 $comments = $post[0]['comments'] ?? 0;
371 if (empty($comments)) {
375 $this->cache->set($cache_key, $comments, Duration::HALF_HOUR);
376 $this->logger->debug('Calculated median comments', ['divider' => $divider, 'median' => $comments]);
380 private function getMedianActivities(int $divider): int
382 $cache_key = 'Channel:getMedianActivities:' . $divider;
383 $activities = $this->cache->get($cache_key);
384 if (!empty($activities)) {
388 $limit = $this->database->count('post-engagement', ["`contact-type` != ? AND `activities` > ?", Contact::TYPE_COMMUNITY, 0]) / $divider;
389 $post = $this->database->selectToArray('post-engagement', ['activities'], ["`contact-type` != ?", Contact::TYPE_COMMUNITY], ['order' => ['activities' => true], 'limit' => [$limit, 1]]);
390 $activities = $post[0]['activities'] ?? 0;
391 if (empty($activities)) {
395 $this->cache->set($cache_key, $activities, Duration::HALF_HOUR);
396 $this->logger->debug('Calculated median activities', ['divider' => $divider, 'median' => $activities]);
400 private function getMedianThreadScore(int $cid, int $divider): int
402 $cache_key = 'Channel:getThreadScore:' . $cid . ':' . $divider;
403 $score = $this->cache->get($cache_key);
404 if (!empty($score)) {
408 $limit = $this->database->count('contact-relation', ["`cid` = ? AND `thread-score` > ?", $cid, 0]) / $divider;
409 $relation = $this->database->selectToArray('contact-relation', ['thread-score'], ['cid' => $cid], ['order' => ['thread-score' => true], 'limit' => [$limit, 1]]);
410 $score = $relation[0]['thread-score'] ?? 0;
415 $this->cache->set($cache_key, $score, Duration::HALF_HOUR);
416 $this->logger->debug('Calculated median score', ['cid' => $cid, 'divider' => $divider, 'median' => $score]);