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\DateTimeFormat;
54 use Friendica\Util\Profiler;
55 use Psr\Log\LoggerInterface;
57 class Channel extends BaseModule
59 protected static $content;
60 protected static $accountTypeString;
61 protected static $accountType;
62 protected static $itemsPerPage;
63 protected static $min_id;
64 protected static $max_id;
65 protected static $item_id;
67 /** @var UserSession */
71 /** @var IManageConfigValues The config */
73 /** @var SystemMessages */
74 protected $systemMessages;
77 /** @var Conversation */
78 protected $conversation;
79 /** @var App\Mode $mode */
81 /** @var IManagePersonalConfigValues */
85 /** @var ChannelFactory */
89 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 = [])
91 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
93 $this->channel = $channel;
94 $this->systemMessages = $systemMessages;
95 $this->database = $database;
96 $this->pConfig = $pConfig;
98 $this->conversation = $conversation;
100 $this->config = $config;
101 $this->cache = $cache;
102 $this->session = $session;
105 protected function content(array $request = []): string
107 if (!$this->session->getLocalUserId()) {
108 return Login::form();
111 $this->parseRequest($request);
113 $t = Renderer::getMarkupTemplate("community.tpl");
114 $o = Renderer::replaceMacros($t, [
119 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
120 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
121 $o .= Renderer::replaceMacros($tpl, ['$reload_uri' => $this->args->getQueryString()]);
124 if (empty($request['mode']) || ($request['mode'] != 'raw')) {
127 foreach ($this->channel->getForUser($this->session->getLocalUserId()) as $tab) {
129 'label' => $tab->label,
130 'url' => 'channel/' . $tab->code,
131 'sel' => self::$content == $tab->code ? 'active' : '',
132 'title' => $tab->description,
133 'id' => 'channel-' . $tab->code . '-tab',
134 'accesskey' => $tab->accessKey,
138 $tab_tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
139 $o .= Renderer::replaceMacros($tab_tpl, ['$tabs' => $tabs]);
141 Nav::setSelected('channel');
143 $this->page['aside'] .= Widget::accountTypes('channel/' . self::$content, self::$accountTypeString);
145 if (!in_array(self::$content, [ChannelEntity::FOLLOWERS, ChannelEntity::FORYOU]) && $this->config->get('system', 'community_no_sharer')) {
146 $path = self::$content;
147 if (!empty($this->parameters['accounttype'])) {
148 $path .= '/' . $this->parameters['accounttype'];
150 $query_parameters = [];
152 if (!empty($request['min_id'])) {
153 $query_parameters['min_id'] = $request['min_id'];
155 if (!empty($request['max_id'])) {
156 $query_parameters['max_id'] = $request['max_id'];
158 if (!empty($request['last_created'])) {
159 $query_parameters['max_id'] = $request['last_created'];
162 $path_all = $path . (!empty($query_parameters) ? '?' . http_build_query($query_parameters) : '');
163 $path_no_sharer = $path . '?' . http_build_query(array_merge($query_parameters, ['no_sharer' => true]));
164 $this->page['aside'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/community_sharer.tpl'), [
165 '$title' => $this->l10n->t('Own Contacts'),
166 '$path_all' => $path_all,
167 '$path_no_sharer' => $path_no_sharer,
168 '$no_sharer' => !empty($request['no_sharer']),
169 '$all' => $this->l10n->t('Include'),
170 '$no_sharer_label' => $this->l10n->t('Hide'),
171 '$base' => 'channel',
175 if (Feature::isEnabled($this->session->getLocalUserId(), 'trending_tags')) {
176 $this->page['aside'] .= TrendingTags::getHTML(self::$content);
179 // We need the editor here to be able to reshare an item.
180 $o .= $this->conversation->statusEditor([], 0, true);
183 $items = $this->getItems($request);
185 if (!$this->database->isResult($items)) {
186 $this->systemMessages->addNotice($this->l10n->t('No results.'));
190 $o .= $this->conversation->render($items, Conversation::MODE_CHANNEL, false, false, 'created', $this->session->getLocalUserId());
192 $pager = new BoundariesPager(
194 $this->args->getQueryString(),
195 $items[0]['created'],
196 $items[count($items) - 1]['created'],
200 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
201 $o .= HTML::scrollLoader();
203 $o .= $pager->renderMinimal(count($items));
210 * Computes module parameters from the request and local configuration
212 * @throws HTTPException\BadRequestException
213 * @throws HTTPException\ForbiddenException
215 protected function parseRequest(array $request)
217 self::$accountTypeString = $request['accounttype'] ?? $this->parameters['accounttype'] ?? '';
218 self::$accountType = User::getAccountTypeByString(self::$accountTypeString);
220 self::$content = $this->parameters['content'] ?? '';
221 if (!self::$content) {
222 self::$content = ChannelEntity::FORYOU;
225 if (!in_array(self::$content, [ChannelEntity::WHATSHOT, ChannelEntity::FORYOU, ChannelEntity::FOLLOWERS, ChannelEntity::SHARERSOFSHARERS, ChannelEntity::IMAGE, ChannelEntity::VIDEO, ChannelEntity::AUDIO, ChannelEntity::LANGUAGE])) {
226 throw new HTTPException\BadRequestException($this->l10n->t('Channel not available.'));
229 if ($this->mode->isMobile()) {
230 self::$itemsPerPage = $this->pConfig->get(
231 $this->session->getLocalUserId(),
233 'itemspage_mobile_network',
234 $this->config->get('system', 'itemspage_network_mobile')
237 self::$itemsPerPage = $this->pConfig->get(
238 $this->session->getLocalUserId(),
241 $this->config->get('system', 'itemspage_network')
245 if (!empty($request['item'])) {
246 $item = Post::selectFirst(['parent-uri-id'], ['id' => $request['item']]);
247 self::$item_id = $item['parent-uri-id'] ?? 0;
252 self::$min_id = $request['min_id'] ?? null;
253 self::$max_id = $request['last_created'] ?? $request['max_id'] ?? null;
257 * Computes the displayed items.
259 * Community pages have a restriction on how many successive posts by the same author can show on any given page,
260 * so we may have to retrieve more content beyond the first query
265 protected function getItems(array $request)
267 if (self::$content == ChannelEntity::WHATSHOT) {
268 if (!is_null(self::$accountType)) {
269 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` = ?", $this->getMedianComments(4), $this->getMedianActivities(4), self::$accountType];
271 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` != ?", $this->getMedianComments(4), $this->getMedianActivities(4), Contact::TYPE_COMMUNITY];
273 } elseif (self::$content == ChannelEntity::FORYOU) {
274 $cid = Contact::getPublicIdByUserId($this->session->getLocalUserId());
276 "(`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `relation-thread-score` > ?) OR
277 ((`comments` >= ? OR `activities` >= ?) AND `owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ?)) OR
278 (`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` IN (?, ?) AND `notify_new_posts`)))",
279 $cid, $this->getMedianRelationThreadScore($cid, 4), $this->getMedianComments(4), $this->getMedianActivities(4), $cid,
280 $this->session->getLocalUserId(), Contact::FRIEND, Contact::SHARING
282 } elseif (self::$content == ChannelEntity::FOLLOWERS) {
283 $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` = ?)", $this->session->getLocalUserId(), Contact::FOLLOWER];
284 } elseif (self::$content == ChannelEntity::SHARERSOFSHARERS) {
285 $cid = Contact::getPublicIdByUserId($this->session->getLocalUserId());
287 // @todo Suggest posts from contacts that are followed most by our followers
289 "`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `last-interaction` > ?
290 AND `relation-cid` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ? AND `relation-thread-score` >= ?)
291 AND NOT `cid` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ?))",
292 DateTimeFormat::utc('now - ' . $this->config->get('channel', 'sharer_interaction_days') .' day'), $cid, $this->getMedianRelationThreadScore($cid, 4), $cid
294 } elseif (self::$content == ChannelEntity::IMAGE) {
295 $condition = ["`media-type` & ?", 1];
296 } elseif (self::$content == ChannelEntity::VIDEO) {
297 $condition = ["`media-type` & ?", 2];
298 } elseif (self::$content == ChannelEntity::AUDIO) {
299 $condition = ["`media-type` & ?", 4];
300 } elseif (self::$content == ChannelEntity::LANGUAGE) {
301 $condition = ["JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?", $this->l10n->convertCodeForLanguageDetection(User::getLanguageCode($this->session->getLocalUserId()))];
304 if (self::$content != ChannelEntity::LANGUAGE) {
305 $condition = $this->addLanguageCondition($condition);
308 $condition[0] .= " AND NOT EXISTS(SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `post-engagement`.`owner-id` AND (`ignored` OR `blocked` OR `collapsed`))";
309 $condition[] = $this->session->getLocalUserId();
311 if ((self::$content != ChannelEntity::WHATSHOT) && !is_null(self::$accountType)) {
312 $condition[0] .= " AND `contact-type` = ?";
313 $condition[] = self::$accountType;
316 $params = ['order' => ['created' => true], 'limit' => self::$itemsPerPage];
318 if (!empty(self::$item_id)) {
319 $condition[0] .= " AND `uri-id` = ?";
320 $condition[] = self::$item_id;
322 if (!empty($request['no_sharer'])) {
323 $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`)";
324 $condition[] = $this->session->getLocalUserId();
327 if (isset(self::$max_id)) {
328 $condition[0] .= " AND `created` < ?";
329 $condition[] = self::$max_id;
332 if (isset(self::$min_id)) {
333 $condition[0] .= " AND `created` > ?";
334 $condition[] = self::$min_id;
336 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
337 if (!isset(self::$max_id)) {
338 $params['order']['created'] = false;
343 $items = $this->database->selectToArray('post-engagement', ['uri-id', 'created'], $condition, $params);
348 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
349 if (empty(self::$item_id) && isset(self::$min_id) && !isset(self::$max_id)) {
350 $items = array_reverse($items);
353 Item::update(['unseen' => false], ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'uri-id' => array_column($items, 'uri-id')]);
358 private function addLanguageCondition(array $condition): array
361 $languages = $this->pConfig->get($this->session->getLocalUserId(), 'channel', 'languages', [User::getLanguageCode($this->session->getLocalUserId())]);
362 $languages = $this->l10n->convertForLanguageDetection($languages);
363 foreach ($languages as $language) {
364 $conditions[] = "JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?";
365 $condition[] = $language;
367 if (!empty($conditions)) {
368 $condition[0] .= " AND (`language` IS NULL OR " . implode(' OR ', $conditions) . ")";
373 private function getMedianComments(int $divider): int
375 $languages = $this->pConfig->get($this->session->getLocalUserId(), 'channel', 'languages', [User::getLanguageCode($this->session->getLocalUserId())]);
376 $cache_key = 'Channel:getMedianComments:' . $divider . ':' . implode(':', $languages);
377 $comments = $this->cache->get($cache_key);
378 if (!empty($comments)) {
382 $condition = ["`contact-type` != ? AND `comments` > ?", Contact::TYPE_COMMUNITY, 0];
383 $condition = $this->addLanguageCondition($condition);
385 $limit = $this->database->count('post-engagement', $condition) / $divider;
386 $post = $this->database->selectToArray('post-engagement', ['comments'], $condition, ['order' => ['comments' => true], 'limit' => [$limit, 1]]);
387 $comments = $post[0]['comments'] ?? 0;
388 if (empty($comments)) {
392 $this->cache->set($cache_key, $comments, Duration::HALF_HOUR);
393 $this->logger->debug('Calculated median comments', ['divider' => $divider, 'languages' => $languages, 'median' => $comments]);
397 private function getMedianActivities(int $divider): int
399 $languages = $this->pConfig->get($this->session->getLocalUserId(), 'channel', 'languages', [User::getLanguageCode($this->session->getLocalUserId())]);
400 $cache_key = 'Channel:getMedianActivities:' . $divider . ':' . implode(':', $languages);
401 $activities = $this->cache->get($cache_key);
402 if (!empty($activities)) {
406 $condition = ["`contact-type` != ? AND `activities` > ?", Contact::TYPE_COMMUNITY, 0];
407 $condition = $this->addLanguageCondition($condition);
409 $limit = $this->database->count('post-engagement', $condition) / $divider;
410 $post = $this->database->selectToArray('post-engagement', ['activities'], $condition, ['order' => ['activities' => true], 'limit' => [$limit, 1]]);
411 $activities = $post[0]['activities'] ?? 0;
412 if (empty($activities)) {
416 $this->cache->set($cache_key, $activities, Duration::HALF_HOUR);
417 $this->logger->debug('Calculated median activities', ['divider' => $divider, 'languages' => $languages, 'median' => $activities]);
421 private function getMedianRelationThreadScore(int $cid, int $divider): int
423 $cache_key = 'Channel:getThreadScore:' . $cid . ':' . $divider;
424 $score = $this->cache->get($cache_key);
425 if (!empty($score)) {
429 $condition = ["`relation-cid` = ? AND `relation-thread-score` > ?", $cid, 0];
431 $limit = $this->database->count('contact-relation', $condition) / $divider;
432 $relation = $this->database->selectToArray('contact-relation', ['relation-thread-score'], $condition, ['order' => ['relation-thread-score' => true], 'limit' => [$limit, 1]]);
433 $score = $relation[0]['relation-thread-score'] ?? 0;
438 $this->cache->set($cache_key, $score, Duration::HALF_HOUR);
439 $this->logger->debug('Calculated median score', ['cid' => $cid, 'divider' => $divider, 'median' => $score]);