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/>.
20 * See update_profile.php for documentation
23 namespace Friendica\Module\Conversation;
25 use Friendica\BaseModule;
26 use Friendica\Content\BoundariesPager;
27 use Friendica\Content\Conversation;
28 use Friendica\Content\Feature;
29 use Friendica\Content\Nav;
30 use Friendica\Content\Text\HTML;
31 use Friendica\Content\Widget;
32 use Friendica\Content\Widget\TrendingTags;
33 use Friendica\Core\Cache\Enum\Duration;
34 use Friendica\Core\Renderer;
35 use Friendica\Database\DBA;
37 use Friendica\Model\Contact;
38 use Friendica\Model\Post;
39 use Friendica\Model\User;
40 use Friendica\Module\Security\Login;
41 use Friendica\Network\HTTPException;
43 class Channel extends BaseModule
45 const WHATSHOT = 'whatshot';
46 const FORYOU = 'foryou';
47 const FOLLOWERS = 'followers';
48 const IMAGE = 'image';
49 const VIDEO = 'video';
50 const AUDIO = 'audio';
55 protected static $content;
56 protected static $accountTypeString;
57 protected static $accountType;
58 protected static $itemsPerPage;
59 protected static $min_id;
60 protected static $max_id;
61 protected static $item_id;
63 protected function content(array $request = []): string
65 if (!DI::userSession()->getLocalUserId()) {
69 $this->parseRequest();
71 $t = Renderer::getMarkupTemplate("community.tpl");
72 $o = Renderer::replaceMacros($t, [
77 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
78 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
79 $o .= Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
82 if (empty($_GET['mode']) || ($_GET['mode'] != 'raw')) {
86 'label' => DI::l10n()->t('For you'),
87 'url' => 'channel/' . self::FORYOU,
88 'sel' => self::$content == self::FORYOU ? 'active' : '',
89 'title' => DI::l10n()->t('Posts from contacts you interact with and who interact with you'),
90 'id' => 'channel-foryou-tab',
95 'label' => DI::l10n()->t('Followers'),
96 'url' => 'channel/' . self::FOLLOWERS,
97 'sel' => self::$content == self::FOLLOWERS ? 'active' : '',
98 'title' => DI::l10n()->t('Posts from your followers that you don\'t follow'),
99 'id' => 'channel-followers-tab',
104 'label' => DI::l10n()->t('Whats Hot'),
105 'url' => 'channel/' . self::WHATSHOT,
106 'sel' => self::$content == self::WHATSHOT ? 'active' : '',
107 'title' => DI::l10n()->t('Posts with a lot of interactions'),
108 'id' => 'channel-whatshot-tab',
113 'label' => DI::l10n()->t('Images'),
114 'url' => 'channel/' . self::IMAGE,
115 'sel' => self::$content == self::IMAGE ? 'active' : '',
116 'title' => DI::l10n()->t('Posts with images'),
117 'id' => 'channel-image-tab',
122 'label' => DI::l10n()->t('Videos'),
123 'url' => 'channel/' . self::VIDEO,
124 'sel' => self::$content == self::VIDEO ? 'active' : '',
125 'title' => DI::l10n()->t('Posts with videos'),
126 'id' => 'channel-video-tab',
131 'label' => DI::l10n()->t('Audio'),
132 'url' => 'channel/' . self::AUDIO,
133 'sel' => self::$content == self::AUDIO ? 'active' : '',
134 'title' => DI::l10n()->t('Posts with audio'),
135 'id' => 'channel-audio-tab',
139 $tab_tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
140 $o .= Renderer::replaceMacros($tab_tpl, ['$tabs' => $tabs]);
142 Nav::setSelected('channel');
144 DI::page()['aside'] .= Widget::accountTypes('channel/' . self::$content, self::$accountTypeString);
146 if (!in_array(self::$content, [self::FOLLOWERS, self::FORYOU]) && DI::config()->get('system', 'community_no_sharer')) {
147 $path = self::$content;
148 if (!empty($this->parameters['accounttype'])) {
149 $path .= '/' . $this->parameters['accounttype'];
151 $query_parameters = [];
153 if (!empty($_GET['min_id'])) {
154 $query_parameters['min_id'] = $_GET['min_id'];
156 if (!empty($_GET['max_id'])) {
157 $query_parameters['max_id'] = $_GET['max_id'];
159 if (!empty($_GET['last_created'])) {
160 $query_parameters['max_id'] = $_GET['last_created'];
163 $path_all = $path . (!empty($query_parameters) ? '?' . http_build_query($query_parameters) : '');
164 $path_no_sharer = $path . '?' . http_build_query(array_merge($query_parameters, ['no_sharer' => true]));
165 DI::page()['aside'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/community_sharer.tpl'), [
166 '$title' => DI::l10n()->t('Own Contacts'),
167 '$path_all' => $path_all,
168 '$path_no_sharer' => $path_no_sharer,
169 '$no_sharer' => !empty($_REQUEST['no_sharer']),
170 '$all' => DI::l10n()->t('Include'),
171 '$no_sharer_label' => DI::l10n()->t('Hide'),
172 '$base' => 'channel',
176 if (Feature::isEnabled(DI::userSession()->getLocalUserId(), 'trending_tags')) {
177 DI::page()['aside'] .= TrendingTags::getHTML(self::$content);
180 // We need the editor here to be able to reshare an item.
181 $o .= DI::conversation()->statusEditor([], 0, true);
184 $items = self::getItems();
186 if (!DBA::isResult($items)) {
187 DI::sysmsg()->addNotice(DI::l10n()->t('No results.'));
191 $o .= DI::conversation()->render($items, Conversation::MODE_CHANNEL, false, false, 'created', DI::userSession()->getLocalUserId());
193 $pager = new BoundariesPager(
195 DI::args()->getQueryString(),
196 $items[0]['created'],
197 $items[count($items) - 1]['created'],
201 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
202 $o .= HTML::scrollLoader();
204 $o .= $pager->renderMinimal(count($items));
211 * Computes module parameters from the request and local configuration
213 * @throws HTTPException\BadRequestException
214 * @throws HTTPException\ForbiddenException
216 protected function parseRequest()
218 self::$accountTypeString = $_GET['accounttype'] ?? $this->parameters['accounttype'] ?? '';
219 self::$accountType = User::getAccountTypeByString(self::$accountTypeString);
221 self::$content = $this->parameters['content'] ?? '';
222 if (!self::$content) {
223 self::$content = self::FORYOU;
226 if (!in_array(self::$content, [self::WHATSHOT, self::FORYOU, self::FOLLOWERS, self::IMAGE, self::VIDEO, self::AUDIO])) {
227 throw new HTTPException\BadRequestException(DI::l10n()->t('Channel not available.'));
230 if (DI::mode()->isMobile()) {
231 self::$itemsPerPage = DI::pConfig()->get(
232 DI::userSession()->getLocalUserId(),
234 'itemspage_mobile_network',
235 DI::config()->get('system', 'itemspage_network_mobile')
238 self::$itemsPerPage = DI::pConfig()->get(
239 DI::userSession()->getLocalUserId(),
242 DI::config()->get('system', 'itemspage_network')
246 if (!empty($_GET['item'])) {
247 $item = Post::selectFirst(['parent-uri-id'], ['id' => $_GET['item']]);
248 self::$item_id = $item['parent-uri-id'] ?? 0;
253 self::$min_id = $_GET['min_id'] ?? null;
254 self::$max_id = $_GET['max_id'] ?? null;
255 self::$max_id = $_GET['last_created'] ?? self::$max_id;
259 * Computes the displayed items.
261 * Community pages have a restriction on how many successive posts by the same author can show on any given page,
262 * so we may have to retrieve more content beyond the first query
267 protected static function getItems()
269 if (self::$content == self::WHATSHOT) {
270 if (!is_null(self::$accountType)) {
271 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` = ?", self::getMedianComments(4), self::getMedianActivities(4), self::$accountType];
273 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` != ?", self::getMedianComments(4), self::getMedianActivities(4), Contact::TYPE_COMMUNITY];
275 } elseif (self::$content == self::FORYOU) {
276 $cid = Contact::getPublicIdByUserId(DI::userSession()->getLocalUserId());
278 $condition = ["(`owner-id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `thread-score` > ?) OR
279 ((`comments` >= ? OR `activities` >= ?) AND `owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` IN (?, ?))) OR
280 ( `owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` IN (?, ?) AND `notify_new_posts`)))",
281 $cid, self::getMedianThreadScore($cid, 4), self::getMedianComments(4), self::getMedianActivities(4), DI::userSession()->getLocalUserId(), Contact::FRIEND, Contact::SHARING,
282 DI::userSession()->getLocalUserId(), Contact::FRIEND, Contact::SHARING];
283 } elseif (self::$content == self::FOLLOWERS) {
284 $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` = ?)", DI::userSession()->getLocalUserId(), Contact::FOLLOWER];
285 } elseif (self::$content == self::IMAGE) {
286 $condition = ["`media-type` & ?", 1];
287 } elseif (self::$content == self::VIDEO) {
288 $condition = ["`media-type` & ?", 2];
289 } elseif (self::$content == self::AUDIO) {
290 $condition = ["`media-type` & ?", 4];
293 $condition[0] .= " AND NOT EXISTS(SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `post-engagement`.`owner-id` AND (`ignored` OR `blocked` OR `collapsed`))";
294 $condition[] = DI::userSession()->getLocalUserId();
296 if ((self::$content != self::WHATSHOT) && !is_null(self::$accountType)) {
297 $condition[0] .= " AND `contact-type` = ?";
298 $condition[] = self::$accountType;
301 $params = ['order' => ['created' => true], 'limit' => self::$itemsPerPage];
303 if (!empty(self::$item_id)) {
304 $condition[0] .= " AND `uri-id` = ?";
305 $condition[] = self::$item_id;
307 if (!empty($_REQUEST['no_sharer'])) {
308 $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`)";
309 $condition[] = DI::userSession()->getLocalUserId();
312 if (isset(self::$max_id)) {
313 $condition[0] .= " AND `created` < ?";
314 $condition[] = self::$max_id;
317 if (isset(self::$min_id)) {
318 $condition[0] .= " AND `created` > ?";
319 $condition[] = self::$min_id;
321 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
322 if (!isset(self::$max_id)) {
323 $params['order']['created'] = false;
328 $items = DBA::selectToArray('post-engagement', ['uri-id', 'created'], $condition, $params);
334 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
335 if (empty(self::$item_id) && isset(self::$min_id) && !isset(self::$max_id)) {
336 $items = array_reverse($items);
342 private static function getMedianComments(int $divider): int
344 $cache_key = 'Channel:getMedianComments:' . $divider;
345 $comments = DI::cache()->get($cache_key);
346 if (!empty($comments)) {
350 $limit = DBA::count('post-engagement', ["`contact-type` != ? AND `comments` > ?", Contact::TYPE_COMMUNITY, 0]) / $divider;
351 $post = DBA::selectToArray('post-engagement', ['comments'], ["`contact-type` != ?", Contact::TYPE_COMMUNITY], ['order' => ['comments' => true], 'limit' => [$limit, 1]]);
352 $comments = $post[0]['comments'] ?? 0;
353 if (empty($comments)) {
357 DI::cache()->set($cache_key, $comments, Duration::HOUR);
361 private static function getMedianActivities(int $divider): int
363 $cache_key = 'Channel:getMedianActivities:' . $divider;
364 $activities = DI::cache()->get($cache_key);
365 if (!empty($activities)) {
369 $limit = DBA::count('post-engagement', ["`contact-type` != ? AND `activities` > ?", Contact::TYPE_COMMUNITY, 0]) / $divider;
370 $post = DBA::selectToArray('post-engagement', ['activities'], ["`contact-type` != ?", Contact::TYPE_COMMUNITY], ['order' => ['activities' => true], 'limit' => [$limit, 1]]);
371 $activities = $post[0]['activities'] ?? 0;
372 if (empty($activities)) {
376 DI::cache()->set($cache_key, $activities, Duration::HOUR);
380 private static function getMedianThreadScore(int $cid, int $divider): int
382 $cache_key = 'Channel:getThreadScore:' . $cid . ':' . $divider;
383 $score = DI::cache()->get($cache_key);
384 if (!empty($score)) {
388 $limit = DBA::count('contact-relation', ["`cid` = ? AND `thread-score` > ?", $cid, 0]) / $divider;
389 $relation = DBA::selectToArray('contact-relation', ['thread-score'], ['cid' => $cid], ['order' => ['thread-score' => true], 'limit' => [$limit, 1]]);
390 $score = $relation[0]['thread-score'] ?? 0;
395 DI::cache()->set($cache_key, $score, Duration::HOUR);