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\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 protected $systemMessages;
79 /** @var Conversation */
80 protected $conversation;
81 /** @var App\Mode $mode */
83 /** @var IManagePersonalConfigValues */
89 public function __construct(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->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')) {
126 'label' => $this->l10n->t('For you'),
127 'url' => 'channel/' . self::FORYOU,
128 'sel' => self::$content == self::FORYOU ? 'active' : '',
129 'title' => $this->l10n->t('Posts from contacts you interact with and who interact with you'),
130 'id' => 'channel-foryou-tab',
135 'label' => $this->l10n->t('Followers'),
136 'url' => 'channel/' . self::FOLLOWERS,
137 'sel' => self::$content == self::FOLLOWERS ? 'active' : '',
138 'title' => $this->l10n->t('Posts from your followers that you don\'t follow'),
139 'id' => 'channel-followers-tab',
144 'label' => $this->l10n->t('Whats Hot'),
145 'url' => 'channel/' . self::WHATSHOT,
146 'sel' => self::$content == self::WHATSHOT ? 'active' : '',
147 'title' => $this->l10n->t('Posts with a lot of interactions'),
148 'id' => 'channel-whatshot-tab',
153 'label' => $this->l10n->t('Images'),
154 'url' => 'channel/' . self::IMAGE,
155 'sel' => self::$content == self::IMAGE ? 'active' : '',
156 'title' => $this->l10n->t('Posts with images'),
157 'id' => 'channel-image-tab',
162 'label' => $this->l10n->t('Videos'),
163 'url' => 'channel/' . self::VIDEO,
164 'sel' => self::$content == self::VIDEO ? 'active' : '',
165 'title' => $this->l10n->t('Posts with videos'),
166 'id' => 'channel-video-tab',
171 'label' => $this->l10n->t('Audio'),
172 'url' => 'channel/' . self::AUDIO,
173 'sel' => self::$content == self::AUDIO ? 'active' : '',
174 'title' => $this->l10n->t('Posts with audio'),
175 'id' => 'channel-audio-tab',
179 $tab_tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
180 $o .= Renderer::replaceMacros($tab_tpl, ['$tabs' => $tabs]);
182 Nav::setSelected('channel');
184 $this->page['aside'] .= Widget::accountTypes('channel/' . self::$content, self::$accountTypeString);
186 if (!in_array(self::$content, [self::FOLLOWERS, self::FORYOU]) && $this->config->get('system', 'community_no_sharer')) {
187 $path = self::$content;
188 if (!empty($this->parameters['accounttype'])) {
189 $path .= '/' . $this->parameters['accounttype'];
191 $query_parameters = [];
193 if (!empty($request['min_id'])) {
194 $query_parameters['min_id'] = $request['min_id'];
196 if (!empty($request['max_id'])) {
197 $query_parameters['max_id'] = $request['max_id'];
199 if (!empty($request['last_created'])) {
200 $query_parameters['max_id'] = $request['last_created'];
203 $path_all = $path . (!empty($query_parameters) ? '?' . http_build_query($query_parameters) : '');
204 $path_no_sharer = $path . '?' . http_build_query(array_merge($query_parameters, ['no_sharer' => true]));
205 $this->page['aside'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/community_sharer.tpl'), [
206 '$title' => $this->l10n->t('Own Contacts'),
207 '$path_all' => $path_all,
208 '$path_no_sharer' => $path_no_sharer,
209 '$no_sharer' => !empty($request['no_sharer']),
210 '$all' => $this->l10n->t('Include'),
211 '$no_sharer_label' => $this->l10n->t('Hide'),
212 '$base' => 'channel',
216 if (Feature::isEnabled($this->session->getLocalUserId(), 'trending_tags')) {
217 $this->page['aside'] .= TrendingTags::getHTML(self::$content);
220 // We need the editor here to be able to reshare an item.
221 $o .= $this->conversation->statusEditor([], 0, true);
224 $items = $this->getItems($request);
226 if (!$this->database->isResult($items)) {
227 $this->systemMessages->addNotice($this->l10n->t('No results.'));
231 $o .= $this->conversation->render($items, Conversation::MODE_CHANNEL, false, false, 'created', $this->session->getLocalUserId());
233 $pager = new BoundariesPager(
235 $this->args->getQueryString(),
236 $items[0]['created'],
237 $items[count($items) - 1]['created'],
241 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
242 $o .= HTML::scrollLoader();
244 $o .= $pager->renderMinimal(count($items));
251 * Computes module parameters from the request and local configuration
253 * @throws HTTPException\BadRequestException
254 * @throws HTTPException\ForbiddenException
256 protected function parseRequest(array $request)
258 self::$accountTypeString = $request['accounttype'] ?? $this->parameters['accounttype'] ?? '';
259 self::$accountType = User::getAccountTypeByString(self::$accountTypeString);
261 self::$content = $this->parameters['content'] ?? '';
262 if (!self::$content) {
263 self::$content = self::FORYOU;
266 if (!in_array(self::$content, [self::WHATSHOT, self::FORYOU, self::FOLLOWERS, self::IMAGE, self::VIDEO, self::AUDIO])) {
267 throw new HTTPException\BadRequestException($this->l10n->t('Channel not available.'));
270 if ($this->mode->isMobile()) {
271 self::$itemsPerPage = $this->pConfig->get(
272 $this->session->getLocalUserId(),
274 'itemspage_mobile_network',
275 $this->config->get('system', 'itemspage_network_mobile')
278 self::$itemsPerPage = $this->pConfig->get(
279 $this->session->getLocalUserId(),
282 $this->config->get('system', 'itemspage_network')
286 if (!empty($request['item'])) {
287 $item = Post::selectFirst(['parent-uri-id'], ['id' => $request['item']]);
288 self::$item_id = $item['parent-uri-id'] ?? 0;
293 self::$min_id = $request['min_id'] ?? null;
294 self::$max_id = $request['last_created'] ?? $request['max_id'] ?? null;
298 * Computes the displayed items.
300 * Community pages have a restriction on how many successive posts by the same author can show on any given page,
301 * so we may have to retrieve more content beyond the first query
306 protected function getItems(array $request)
308 if (self::$content == self::WHATSHOT) {
309 if (!is_null(self::$accountType)) {
310 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` = ?", $this->getMedianComments(4), $this->getMedianActivities(4), self::$accountType];
312 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` != ?", $this->getMedianComments(4), $this->getMedianActivities(4), Contact::TYPE_COMMUNITY];
314 } elseif (self::$content == self::FORYOU) {
315 $cid = Contact::getPublicIdByUserId($this->session->getLocalUserId());
317 $condition = ["(`owner-id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `thread-score` > ?) OR
318 ((`comments` >= ? OR `activities` >= ?) AND `owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` IN (?, ?))) OR
319 ( `owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` IN (?, ?) AND `notify_new_posts`)))",
320 $cid, $this->getMedianThreadScore($cid, 4), $this->getMedianComments(4), $this->getMedianActivities(4), $this->session->getLocalUserId(), Contact::FRIEND, Contact::SHARING,
321 $this->session->getLocalUserId(), Contact::FRIEND, Contact::SHARING];
322 } elseif (self::$content == self::FOLLOWERS) {
323 $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` = ?)", $this->session->getLocalUserId(), Contact::FOLLOWER];
324 } elseif (self::$content == self::IMAGE) {
325 $condition = ["`media-type` & ?", 1];
326 } elseif (self::$content == self::VIDEO) {
327 $condition = ["`media-type` & ?", 2];
328 } elseif (self::$content == self::AUDIO) {
329 $condition = ["`media-type` & ?", 4];
332 $condition[0] .= " AND NOT EXISTS(SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `post-engagement`.`owner-id` AND (`ignored` OR `blocked` OR `collapsed`))";
333 $condition[] = $this->session->getLocalUserId();
335 if ((self::$content != self::WHATSHOT) && !is_null(self::$accountType)) {
336 $condition[0] .= " AND `contact-type` = ?";
337 $condition[] = self::$accountType;
340 $params = ['order' => ['created' => true], 'limit' => self::$itemsPerPage];
342 if (!empty(self::$item_id)) {
343 $condition[0] .= " AND `uri-id` = ?";
344 $condition[] = self::$item_id;
346 if (!empty($request['no_sharer'])) {
347 $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`)";
348 $condition[] = $this->session->getLocalUserId();
351 if (isset(self::$max_id)) {
352 $condition[0] .= " AND `created` < ?";
353 $condition[] = self::$max_id;
356 if (isset(self::$min_id)) {
357 $condition[0] .= " AND `created` > ?";
358 $condition[] = self::$min_id;
360 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
361 if (!isset(self::$max_id)) {
362 $params['order']['created'] = false;
367 $items = $this->database->selectToArray('post-engagement', ['uri-id', 'created'], $condition, $params);
373 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
374 if (empty(self::$item_id) && isset(self::$min_id) && !isset(self::$max_id)) {
375 $items = array_reverse($items);
381 private function getMedianComments(int $divider): int
383 $cache_key = 'Channel:getMedianComments:' . $divider;
384 $comments = $this->cache->get($cache_key);
385 if (!empty($comments)) {
389 $limit = $this->database->count('post-engagement', ["`contact-type` != ? AND `comments` > ?", Contact::TYPE_COMMUNITY, 0]) / $divider;
390 $post = $this->database->selectToArray('post-engagement', ['comments'], ["`contact-type` != ?", Contact::TYPE_COMMUNITY], ['order' => ['comments' => true], 'limit' => [$limit, 1]]);
391 $comments = $post[0]['comments'] ?? 0;
392 if (empty($comments)) {
396 $this->cache->set($cache_key, $comments, Duration::HOUR);
400 private function getMedianActivities(int $divider): int
402 $cache_key = 'Channel:getMedianActivities:' . $divider;
403 $activities = $this->cache->get($cache_key);
404 if (!empty($activities)) {
408 $limit = $this->database->count('post-engagement', ["`contact-type` != ? AND `activities` > ?", Contact::TYPE_COMMUNITY, 0]) / $divider;
409 $post = $this->database->selectToArray('post-engagement', ['activities'], ["`contact-type` != ?", Contact::TYPE_COMMUNITY], ['order' => ['activities' => true], 'limit' => [$limit, 1]]);
410 $activities = $post[0]['activities'] ?? 0;
411 if (empty($activities)) {
415 $this->cache->set($cache_key, $activities, Duration::HOUR);
419 private function getMedianThreadScore(int $cid, int $divider): int
421 $cache_key = 'Channel:getThreadScore:' . $cid . ':' . $divider;
422 $score = $this->cache->get($cache_key);
423 if (!empty($score)) {
427 $limit = $this->database->count('contact-relation', ["`cid` = ? AND `thread-score` > ?", $cid, 0]) / $divider;
428 $relation = $this->database->selectToArray('contact-relation', ['thread-score'], ['cid' => $cid], ['order' => ['thread-score' => true], 'limit' => [$limit, 1]]);
429 $score = $relation[0]['thread-score'] ?? 0;
434 $this->cache->set($cache_key, $score, Duration::HOUR);