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\Conversation\Entity\Channel as ChannelEntity;
30 use Friendica\Content\Conversation\Factory\Channel as ChannelFactory;
31 use Friendica\Content\Feature;
32 use Friendica\Content\Nav;
33 use Friendica\Content\Text\HTML;
34 use Friendica\Content\Widget;
35 use Friendica\Content\Widget\TrendingTags;
36 use Friendica\Core\Cache\Capability\ICanCache;
37 use Friendica\Core\Cache\Enum\Duration;
38 use Friendica\Core\Config\Capability\IManageConfigValues;
39 use Friendica\Core\L10n;
40 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
41 use Friendica\Core\Renderer;
42 use Friendica\Core\Session\Capability\IHandleUserSessions;
43 use Friendica\Model\Contact;
44 use Friendica\Model\Post;
45 use Friendica\Model\User;
46 use Friendica\Module\Security\Login;
47 use Friendica\Network\HTTPException;
48 use Friendica\Core\Session\Model\UserSession;
49 use Friendica\Database\Database;
50 use Friendica\Model\Item;
51 use Friendica\Module\Response;
52 use Friendica\Navigation\SystemMessages;
53 use Friendica\Util\Profiler;
54 use Psr\Log\LoggerInterface;
56 class Channel extends BaseModule
58 protected static $content;
59 protected static $accountTypeString;
60 protected static $accountType;
61 protected static $itemsPerPage;
62 protected static $min_id;
63 protected static $max_id;
64 protected static $item_id;
66 /** @var UserSession */
70 /** @var IManageConfigValues The config */
72 /** @var SystemMessages */
73 protected $systemMessages;
76 /** @var Conversation */
77 protected $conversation;
78 /** @var App\Mode $mode */
80 /** @var IManagePersonalConfigValues */
84 /** @var ChannelFactory */
88 public function __construct(ChannelFactory $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 = [])
90 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
92 $this->channel = $channel;
93 $this->systemMessages = $systemMessages;
94 $this->database = $database;
95 $this->pConfig = $pConfig;
97 $this->conversation = $conversation;
99 $this->config = $config;
100 $this->cache = $cache;
101 $this->session = $session;
104 protected function content(array $request = []): string
106 if (!$this->session->getLocalUserId()) {
107 return Login::form();
110 $this->parseRequest($request);
112 $t = Renderer::getMarkupTemplate("community.tpl");
113 $o = Renderer::replaceMacros($t, [
118 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
119 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
120 $o .= Renderer::replaceMacros($tpl, ['$reload_uri' => $this->args->getQueryString()]);
123 if (empty($request['mode']) || ($request['mode'] != 'raw')) {
126 foreach ($this->channel->getForUser($this->session->getLocalUserId()) as $tab) {
128 'label' => $tab->label,
129 'url' => 'channel/' . $tab->code,
130 'sel' => self::$content == $tab->code ? 'active' : '',
131 'title' => $tab->description,
132 'id' => 'channel-' . $tab->code . '-tab',
133 'accesskey' => $tab->accessKey,
137 $tab_tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
138 $o .= Renderer::replaceMacros($tab_tpl, ['$tabs' => $tabs]);
140 Nav::setSelected('channel');
142 $this->page['aside'] .= Widget::accountTypes('channel/' . self::$content, self::$accountTypeString);
144 if (!in_array(self::$content, [ChannelEntity::FOLLOWERS, ChannelEntity::FORYOU]) && $this->config->get('system', 'community_no_sharer')) {
145 $path = self::$content;
146 if (!empty($this->parameters['accounttype'])) {
147 $path .= '/' . $this->parameters['accounttype'];
149 $query_parameters = [];
151 if (!empty($request['min_id'])) {
152 $query_parameters['min_id'] = $request['min_id'];
154 if (!empty($request['max_id'])) {
155 $query_parameters['max_id'] = $request['max_id'];
157 if (!empty($request['last_created'])) {
158 $query_parameters['max_id'] = $request['last_created'];
161 $path_all = $path . (!empty($query_parameters) ? '?' . http_build_query($query_parameters) : '');
162 $path_no_sharer = $path . '?' . http_build_query(array_merge($query_parameters, ['no_sharer' => true]));
163 $this->page['aside'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/community_sharer.tpl'), [
164 '$title' => $this->l10n->t('Own Contacts'),
165 '$path_all' => $path_all,
166 '$path_no_sharer' => $path_no_sharer,
167 '$no_sharer' => !empty($request['no_sharer']),
168 '$all' => $this->l10n->t('Include'),
169 '$no_sharer_label' => $this->l10n->t('Hide'),
170 '$base' => 'channel',
174 if (Feature::isEnabled($this->session->getLocalUserId(), 'trending_tags')) {
175 $this->page['aside'] .= TrendingTags::getHTML(self::$content);
178 // We need the editor here to be able to reshare an item.
179 $o .= $this->conversation->statusEditor([], 0, true);
182 $items = $this->getItems($request);
184 if (!$this->database->isResult($items)) {
185 $this->systemMessages->addNotice($this->l10n->t('No results.'));
189 $o .= $this->conversation->render($items, Conversation::MODE_CHANNEL, false, false, 'created', $this->session->getLocalUserId());
191 $pager = new BoundariesPager(
193 $this->args->getQueryString(),
194 $items[0]['created'],
195 $items[count($items) - 1]['created'],
199 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
200 $o .= HTML::scrollLoader();
202 $o .= $pager->renderMinimal(count($items));
209 * Computes module parameters from the request and local configuration
211 * @throws HTTPException\BadRequestException
212 * @throws HTTPException\ForbiddenException
214 protected function parseRequest(array $request)
216 self::$accountTypeString = $request['accounttype'] ?? $this->parameters['accounttype'] ?? '';
217 self::$accountType = User::getAccountTypeByString(self::$accountTypeString);
219 self::$content = $this->parameters['content'] ?? '';
220 if (!self::$content) {
221 self::$content = ChannelEntity::FORYOU;
224 if (!in_array(self::$content, [ChannelEntity::WHATSHOT, ChannelEntity::FORYOU, ChannelEntity::FOLLOWERS, ChannelEntity::IMAGE, ChannelEntity::VIDEO, ChannelEntity::AUDIO, ChannelEntity::LANGUAGE])) {
225 throw new HTTPException\BadRequestException($this->l10n->t('Channel not available.'));
228 if ($this->mode->isMobile()) {
229 self::$itemsPerPage = $this->pConfig->get(
230 $this->session->getLocalUserId(),
232 'itemspage_mobile_network',
233 $this->config->get('system', 'itemspage_network_mobile')
236 self::$itemsPerPage = $this->pConfig->get(
237 $this->session->getLocalUserId(),
240 $this->config->get('system', 'itemspage_network')
244 if (!empty($request['item'])) {
245 $item = Post::selectFirst(['parent-uri-id'], ['id' => $request['item']]);
246 self::$item_id = $item['parent-uri-id'] ?? 0;
251 self::$min_id = $request['min_id'] ?? null;
252 self::$max_id = $request['last_created'] ?? $request['max_id'] ?? null;
256 * Computes the displayed items.
258 * Community pages have a restriction on how many successive posts by the same author can show on any given page,
259 * so we may have to retrieve more content beyond the first query
264 protected function getItems(array $request)
266 if (self::$content == ChannelEntity::WHATSHOT) {
267 if (!is_null(self::$accountType)) {
268 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` = ?", $this->getMedianComments(4), $this->getMedianActivities(4), self::$accountType];
270 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` != ?", $this->getMedianComments(4), $this->getMedianActivities(4), Contact::TYPE_COMMUNITY];
272 } elseif (self::$content == ChannelEntity::FORYOU) {
273 $cid = Contact::getPublicIdByUserId($this->session->getLocalUserId());
275 $condition = ["(`owner-id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `thread-score` > ?) OR
276 ((`comments` >= ? OR `activities` >= ?) AND `owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` IN (?, ?))) OR
277 ( `owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` IN (?, ?) AND `notify_new_posts`)))",
278 $cid, $this->getMedianThreadScore($cid, 4), $this->getMedianComments(4), $this->getMedianActivities(4), $this->session->getLocalUserId(), Contact::FRIEND, Contact::SHARING,
279 $this->session->getLocalUserId(), Contact::FRIEND, Contact::SHARING];
280 } elseif (self::$content == ChannelEntity::FOLLOWERS) {
281 $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` = ?)", $this->session->getLocalUserId(), Contact::FOLLOWER];
282 } elseif (self::$content == ChannelEntity::IMAGE) {
283 $condition = ["`media-type` & ?", 1];
284 } elseif (self::$content == ChannelEntity::VIDEO) {
285 $condition = ["`media-type` & ?", 2];
286 } elseif (self::$content == ChannelEntity::AUDIO) {
287 $condition = ["`media-type` & ?", 4];
288 } elseif (self::$content == ChannelEntity::LANGUAGE) {
289 $condition = ["JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?", $this->l10n->convertCodeForLanguageDetection(User::getLanguageCode($this->session->getLocalUserId()))];
292 if (self::$content != ChannelEntity::LANGUAGE) {
293 $condition = $this->addLanguageCondition($condition);
296 $condition[0] .= " AND NOT EXISTS(SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `post-engagement`.`owner-id` AND (`ignored` OR `blocked` OR `collapsed`))";
297 $condition[] = $this->session->getLocalUserId();
299 if ((self::$content != ChannelEntity::WHATSHOT) && !is_null(self::$accountType)) {
300 $condition[0] .= " AND `contact-type` = ?";
301 $condition[] = self::$accountType;
304 $params = ['order' => ['created' => true], 'limit' => self::$itemsPerPage];
306 if (!empty(self::$item_id)) {
307 $condition[0] .= " AND `uri-id` = ?";
308 $condition[] = self::$item_id;
310 if (!empty($request['no_sharer'])) {
311 $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`)";
312 $condition[] = $this->session->getLocalUserId();
315 if (isset(self::$max_id)) {
316 $condition[0] .= " AND `created` < ?";
317 $condition[] = self::$max_id;
320 if (isset(self::$min_id)) {
321 $condition[0] .= " AND `created` > ?";
322 $condition[] = self::$min_id;
324 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
325 if (!isset(self::$max_id)) {
326 $params['order']['created'] = false;
331 $items = $this->database->selectToArray('post-engagement', ['uri-id', 'created'], $condition, $params);
336 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
337 if (empty(self::$item_id) && isset(self::$min_id) && !isset(self::$max_id)) {
338 $items = array_reverse($items);
341 Item::update(['unseen' => false], ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'uri-id' => array_column($items, 'uri-id')]);
346 private function addLanguageCondition(array $condition): array
349 $languages = $this->pConfig->get($this->session->getLocalUserId(), 'channel', 'languages', [User::getLanguageCode($this->session->getLocalUserId())]);
350 $languages = $this->l10n->convertForLanguageDetection($languages);
351 foreach ($languages as $language) {
352 $conditions[] = "JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?";
353 $condition[] = $language;
355 if (!empty($conditions)) {
356 $condition[0] .= " AND (`language` IS NULL OR " . implode(' OR ', $conditions) . ")";
361 private function getMedianComments(int $divider): int
363 $cache_key = 'Channel:getMedianComments:' . $divider;
364 $comments = $this->cache->get($cache_key);
365 if (!empty($comments)) {
369 $limit = $this->database->count('post-engagement', ["`contact-type` != ? AND `comments` > ?", Contact::TYPE_COMMUNITY, 0]) / $divider;
370 $post = $this->database->selectToArray('post-engagement', ['comments'], ["`contact-type` != ?", Contact::TYPE_COMMUNITY], ['order' => ['comments' => true], 'limit' => [$limit, 1]]);
371 $comments = $post[0]['comments'] ?? 0;
372 if (empty($comments)) {
376 $this->cache->set($cache_key, $comments, Duration::HALF_HOUR);
377 $this->logger->debug('Calculated median comments', ['divider' => $divider, 'median' => $comments]);
381 private function getMedianActivities(int $divider): int
383 $cache_key = 'Channel:getMedianActivities:' . $divider;
384 $activities = $this->cache->get($cache_key);
385 if (!empty($activities)) {
389 $limit = $this->database->count('post-engagement', ["`contact-type` != ? AND `activities` > ?", Contact::TYPE_COMMUNITY, 0]) / $divider;
390 $post = $this->database->selectToArray('post-engagement', ['activities'], ["`contact-type` != ?", Contact::TYPE_COMMUNITY], ['order' => ['activities' => true], 'limit' => [$limit, 1]]);
391 $activities = $post[0]['activities'] ?? 0;
392 if (empty($activities)) {
396 $this->cache->set($cache_key, $activities, Duration::HALF_HOUR);
397 $this->logger->debug('Calculated median activities', ['divider' => $divider, 'median' => $activities]);
401 private function getMedianThreadScore(int $cid, int $divider): int
403 $cache_key = 'Channel:getThreadScore:' . $cid . ':' . $divider;
404 $score = $this->cache->get($cache_key);
405 if (!empty($score)) {
409 $limit = $this->database->count('contact-relation', ["`cid` = ? AND `thread-score` > ?", $cid, 0]) / $divider;
410 $relation = $this->database->selectToArray('contact-relation', ['thread-score'], ['cid' => $cid], ['order' => ['thread-score' => true], 'limit' => [$limit, 1]]);
411 $score = $relation[0]['thread-score'] ?? 0;
416 $this->cache->set($cache_key, $score, Duration::HALF_HOUR);
417 $this->logger->debug('Calculated median score', ['cid' => $cid, 'divider' => $divider, 'median' => $score]);