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/>.
21 namespace Friendica\Module\Conversation;
23 use Friendica\BaseModule;
24 use Friendica\Content\BoundariesPager;
25 use Friendica\Content\Conversation;
26 use Friendica\Content\Feature;
27 use Friendica\Content\Nav;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Content\Widget;
30 use Friendica\Content\Widget\TrendingTags;
31 use Friendica\Core\Cache\Enum\Duration;
32 use Friendica\Core\Logger;
33 use Friendica\Core\Renderer;
34 use Friendica\Database\DBA;
36 use Friendica\Model\Contact;
37 use Friendica\Model\Post;
38 use Friendica\Model\User;
39 use Friendica\Module\Security\Login;
40 use Friendica\Network\HTTPException;
42 class Channel extends BaseModule
44 const WHATSHOT = 'whatshot';
45 const FORYOU = 'foryou';
46 const FOLLOWERS = 'followers';
47 const IMAGE = 'image';
48 const VIDEO = 'video';
49 const AUDIO = 'audio';
51 protected static $content;
52 protected static $accountTypeString;
53 protected static $accountType;
54 protected static $itemsPerPage;
55 protected static $min_id;
56 protected static $max_id;
57 protected static $item_id;
59 protected function content(array $request = []): string
61 if (!DI::userSession()->getLocalUserId()) {
65 $this->parseRequest($request);
67 $t = Renderer::getMarkupTemplate("community.tpl");
68 $o = Renderer::replaceMacros($t, [
73 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
74 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
75 $o .= Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
78 if (empty($request['mode']) || ($request['mode'] != 'raw')) {
82 'label' => DI::l10n()->t('For you'),
83 'url' => 'channel/' . self::FORYOU,
84 'sel' => self::$content == self::FORYOU ? 'active' : '',
85 'title' => DI::l10n()->t('Posts from contacts you interact with and who interact with you'),
86 'id' => 'channel-foryou-tab',
91 'label' => DI::l10n()->t('Followers'),
92 'url' => 'channel/' . self::FOLLOWERS,
93 'sel' => self::$content == self::FOLLOWERS ? 'active' : '',
94 'title' => DI::l10n()->t('Posts from your followers that you don\'t follow'),
95 'id' => 'channel-followers-tab',
100 'label' => DI::l10n()->t('Whats Hot'),
101 'url' => 'channel/' . self::WHATSHOT,
102 'sel' => self::$content == self::WHATSHOT ? 'active' : '',
103 'title' => DI::l10n()->t('Posts with a lot of interactions'),
104 'id' => 'channel-whatshot-tab',
109 'label' => DI::l10n()->t('Images'),
110 'url' => 'channel/' . self::IMAGE,
111 'sel' => self::$content == self::IMAGE ? 'active' : '',
112 'title' => DI::l10n()->t('Posts with images'),
113 'id' => 'channel-image-tab',
118 'label' => DI::l10n()->t('Videos'),
119 'url' => 'channel/' . self::VIDEO,
120 'sel' => self::$content == self::VIDEO ? 'active' : '',
121 'title' => DI::l10n()->t('Posts with videos'),
122 'id' => 'channel-video-tab',
127 'label' => DI::l10n()->t('Audio'),
128 'url' => 'channel/' . self::AUDIO,
129 'sel' => self::$content == self::AUDIO ? 'active' : '',
130 'title' => DI::l10n()->t('Posts with audio'),
131 'id' => 'channel-audio-tab',
135 $tab_tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
136 $o .= Renderer::replaceMacros($tab_tpl, ['$tabs' => $tabs]);
138 Nav::setSelected('channel');
140 DI::page()['aside'] .= Widget::accountTypes('channel/' . self::$content, self::$accountTypeString);
142 if (!in_array(self::$content, [self::FOLLOWERS, self::FORYOU]) && DI::config()->get('system', 'community_no_sharer')) {
143 $path = self::$content;
144 if (!empty($this->parameters['accounttype'])) {
145 $path .= '/' . $this->parameters['accounttype'];
147 $query_parameters = [];
149 if (!empty($request['min_id'])) {
150 $query_parameters['min_id'] = $request['min_id'];
152 if (!empty($request['max_id'])) {
153 $query_parameters['max_id'] = $request['max_id'];
155 if (!empty($request['last_created'])) {
156 $query_parameters['max_id'] = $request['last_created'];
159 $path_all = $path . (!empty($query_parameters) ? '?' . http_build_query($query_parameters) : '');
160 $path_no_sharer = $path . '?' . http_build_query(array_merge($query_parameters, ['no_sharer' => true]));
161 DI::page()['aside'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/community_sharer.tpl'), [
162 '$title' => DI::l10n()->t('Own Contacts'),
163 '$path_all' => $path_all,
164 '$path_no_sharer' => $path_no_sharer,
165 '$no_sharer' => !empty($request['no_sharer']),
166 '$all' => DI::l10n()->t('Include'),
167 '$no_sharer_label' => DI::l10n()->t('Hide'),
168 '$base' => 'channel',
172 if (Feature::isEnabled(DI::userSession()->getLocalUserId(), 'trending_tags')) {
173 DI::page()['aside'] .= TrendingTags::getHTML(self::$content);
176 // We need the editor here to be able to reshare an item.
177 $o .= DI::conversation()->statusEditor([], 0, true);
180 $items = self::getItems($request);
182 if (!DBA::isResult($items)) {
183 DI::sysmsg()->addNotice(DI::l10n()->t('No results.'));
187 $o .= DI::conversation()->render($items, Conversation::MODE_CHANNEL, false, false, 'created', DI::userSession()->getLocalUserId());
189 $pager = new BoundariesPager(
191 DI::args()->getQueryString(),
192 $items[0]['created'],
193 $items[count($items) - 1]['created'],
197 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
198 $o .= HTML::scrollLoader();
200 $o .= $pager->renderMinimal(count($items));
207 * Computes module parameters from the request and local configuration
209 * @throws HTTPException\BadRequestException
210 * @throws HTTPException\ForbiddenException
212 protected function parseRequest(array $request)
214 self::$accountTypeString = $request['accounttype'] ?? $this->parameters['accounttype'] ?? '';
215 self::$accountType = User::getAccountTypeByString(self::$accountTypeString);
217 self::$content = $this->parameters['content'] ?? '';
218 if (!self::$content) {
219 self::$content = self::FORYOU;
222 if (!in_array(self::$content, [self::WHATSHOT, self::FORYOU, self::FOLLOWERS, self::IMAGE, self::VIDEO, self::AUDIO])) {
223 throw new HTTPException\BadRequestException(DI::l10n()->t('Channel not available.'));
226 if (DI::mode()->isMobile()) {
227 self::$itemsPerPage = DI::pConfig()->get(
228 DI::userSession()->getLocalUserId(),
230 'itemspage_mobile_network',
231 DI::config()->get('system', 'itemspage_network_mobile')
234 self::$itemsPerPage = DI::pConfig()->get(
235 DI::userSession()->getLocalUserId(),
238 DI::config()->get('system', 'itemspage_network')
242 if (!empty($request['item'])) {
243 $item = Post::selectFirst(['parent-uri-id'], ['id' => $request['item']]);
244 self::$item_id = $item['parent-uri-id'] ?? 0;
249 Logger::debug('Blubb', ['get' => $request]);
250 self::$min_id = $request['min_id'] ?? null;
251 self::$max_id = $request['max_id'] ?? null;
252 self::$max_id = $request['last_created'] ?? self::$max_id;
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 static function getItems(array $request)
266 if (self::$content == self::WHATSHOT) {
267 if (!is_null(self::$accountType)) {
268 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` = ?", self::getMedianComments(4), self::getMedianActivities(4), self::$accountType];
270 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` != ?", self::getMedianComments(4), self::getMedianActivities(4), Contact::TYPE_COMMUNITY];
272 } elseif (self::$content == self::FORYOU) {
273 $cid = Contact::getPublicIdByUserId(DI::userSession()->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, self::getMedianThreadScore($cid, 4), self::getMedianComments(4), self::getMedianActivities(4), DI::userSession()->getLocalUserId(), Contact::FRIEND, Contact::SHARING,
279 DI::userSession()->getLocalUserId(), Contact::FRIEND, Contact::SHARING];
280 } elseif (self::$content == self::FOLLOWERS) {
281 $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` = ?)", DI::userSession()->getLocalUserId(), Contact::FOLLOWER];
282 } elseif (self::$content == self::IMAGE) {
283 $condition = ["`media-type` & ?", 1];
284 } elseif (self::$content == self::VIDEO) {
285 $condition = ["`media-type` & ?", 2];
286 } elseif (self::$content == self::AUDIO) {
287 $condition = ["`media-type` & ?", 4];
290 $condition[0] .= " AND NOT EXISTS(SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `post-engagement`.`owner-id` AND (`ignored` OR `blocked` OR `collapsed`))";
291 $condition[] = DI::userSession()->getLocalUserId();
293 if ((self::$content != self::WHATSHOT) && !is_null(self::$accountType)) {
294 $condition[0] .= " AND `contact-type` = ?";
295 $condition[] = self::$accountType;
298 $params = ['order' => ['created' => true], 'limit' => self::$itemsPerPage];
300 if (!empty(self::$item_id)) {
301 $condition[0] .= " AND `uri-id` = ?";
302 $condition[] = self::$item_id;
304 if (!empty($request['no_sharer'])) {
305 $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`)";
306 $condition[] = DI::userSession()->getLocalUserId();
309 if (isset(self::$max_id)) {
310 $condition[0] .= " AND `created` < ?";
311 $condition[] = self::$max_id;
314 if (isset(self::$min_id)) {
315 $condition[0] .= " AND `created` > ?";
316 $condition[] = self::$min_id;
318 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
319 if (!isset(self::$max_id)) {
320 $params['order']['created'] = false;
325 $items = DBA::selectToArray('post-engagement', ['uri-id', 'created'], $condition, $params);
331 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
332 if (empty(self::$item_id) && isset(self::$min_id) && !isset(self::$max_id)) {
333 $items = array_reverse($items);
339 private static function getMedianComments(int $divider): int
341 $cache_key = 'Channel:getMedianComments:' . $divider;
342 $comments = DI::cache()->get($cache_key);
343 if (!empty($comments)) {
347 $limit = DBA::count('post-engagement', ["`contact-type` != ? AND `comments` > ?", Contact::TYPE_COMMUNITY, 0]) / $divider;
348 $post = DBA::selectToArray('post-engagement', ['comments'], ["`contact-type` != ?", Contact::TYPE_COMMUNITY], ['order' => ['comments' => true], 'limit' => [$limit, 1]]);
349 $comments = $post[0]['comments'] ?? 0;
350 if (empty($comments)) {
354 DI::cache()->set($cache_key, $comments, Duration::HOUR);
358 private static function getMedianActivities(int $divider): int
360 $cache_key = 'Channel:getMedianActivities:' . $divider;
361 $activities = DI::cache()->get($cache_key);
362 if (!empty($activities)) {
366 $limit = DBA::count('post-engagement', ["`contact-type` != ? AND `activities` > ?", Contact::TYPE_COMMUNITY, 0]) / $divider;
367 $post = DBA::selectToArray('post-engagement', ['activities'], ["`contact-type` != ?", Contact::TYPE_COMMUNITY], ['order' => ['activities' => true], 'limit' => [$limit, 1]]);
368 $activities = $post[0]['activities'] ?? 0;
369 if (empty($activities)) {
373 DI::cache()->set($cache_key, $activities, Duration::HOUR);
377 private static function getMedianThreadScore(int $cid, int $divider): int
379 $cache_key = 'Channel:getThreadScore:' . $cid . ':' . $divider;
380 $score = DI::cache()->get($cache_key);
381 if (!empty($score)) {
385 $limit = DBA::count('contact-relation', ["`cid` = ? AND `thread-score` > ?", $cid, 0]) / $divider;
386 $relation = DBA::selectToArray('contact-relation', ['thread-score'], ['cid' => $cid], ['order' => ['thread-score' => true], 'limit' => [$limit, 1]]);
387 $score = $relation[0]['thread-score'] ?? 0;
392 DI::cache()->set($cache_key, $score, Duration::HOUR);