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\Conversation\Collection\Timelines;
28 use Friendica\Content\Conversation\Entity\Timeline as TimelineEntity;
29 use Friendica\Core\Cache\Capability\ICanCache;
30 use Friendica\Core\Cache\Enum\Duration;
31 use Friendica\Core\Config\Capability\IManageConfigValues;
32 use Friendica\Core\L10n;
33 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
34 use Friendica\Core\Renderer;
35 use Friendica\Core\Session\Capability\IHandleUserSessions;
36 use Friendica\Model\Contact;
37 use Friendica\Model\User;
38 use Friendica\Database\Database;
39 use Friendica\Database\DBA;
40 use Friendica\Model\Item;
41 use Friendica\Model\Post;
42 use Friendica\Module\Response;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\Profiler;
45 use Psr\Log\LoggerInterface;
47 class Timeline extends BaseModule
50 protected $selectedTab;
56 protected $accountTypeString;
58 protected $accountType;
62 protected $itemsPerPage;
66 /** @var App\Mode $mode */
68 /** @var IHandleUserSessions */
72 /** @var IManagePersonalConfigValues */
74 /** @var IManageConfigValues The config */
79 public function __construct(Mode $mode, IHandleUserSessions $session, Database $database, IManagePersonalConfigValues $pConfig, IManageConfigValues $config, ICanCache $cache, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
81 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
84 $this->session = $session;
85 $this->database = $database;
86 $this->pConfig = $pConfig;
87 $this->config = $config;
88 $this->cache = $cache;
92 * Computes module parameters from the request and local configuration
94 * @throws HTTPException\BadRequestException
95 * @throws HTTPException\ForbiddenException
97 protected function parseRequest(array $request)
99 $this->logger->debug('Got request', $request);
100 $this->selectedTab = $this->parameters['content'] ?? $request['channel'] ?? '';
102 $this->accountTypeString = $request['accounttype'] ?? $this->parameters['accounttype'] ?? '';
103 $this->accountType = User::getAccountTypeByString($this->accountTypeString);
105 if ($this->mode->isMobile()) {
106 $this->itemsPerPage = $this->pConfig->get(
107 $this->session->getLocalUserId(),
109 'itemspage_mobile_network',
110 $this->config->get('system', 'itemspage_network_mobile')
113 $this->itemsPerPage = $this->pConfig->get(
114 $this->session->getLocalUserId(),
117 $this->config->get('system', 'itemspage_network')
121 if (!empty($request['item'])) {
122 $item = Post::selectFirst(['parent', 'parent-uri-id'], ['id' => $request['item']]);
123 $this->itemUriId = $item['parent-uri-id'] ?? 0;
125 $this->itemUriId = 0;
128 $this->minId = $request['min_id'] ?? null;
129 $this->maxId = $request['max_id'] ?? null;
131 $this->noSharer = !empty($request['no_sharer']);
134 protected function getNoSharerWidget(string $base): string
136 $path = $this->selectedTab;
137 if (!empty($this->accountTypeString)) {
138 $path .= '/' . $this->accountTypeString;
140 $query_parameters = [];
142 if (!empty($this->minId)) {
143 $query_parameters['min_id'] = $this->minId;
145 if (!empty($this->maxId)) {
146 $query_parameters['max_id'] = $this->maxId;
149 $path_all = $path . (!empty($query_parameters) ? '?' . http_build_query($query_parameters) : '');
150 $path_no_sharer = $path . '?' . http_build_query(array_merge($query_parameters, ['no_sharer' => true]));
151 return Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/community_sharer.tpl'), [
152 '$title' => $this->l10n->t('Own Contacts'),
153 '$path_all' => $path_all,
154 '$path_no_sharer' => $path_no_sharer,
155 '$no_sharer' => $this->noSharer,
156 '$all' => $this->l10n->t('Include'),
157 '$no_sharer_label' => $this->l10n->t('Hide'),
162 protected function getTabArray(Timelines $timelines, string $prefix, string $parameter = ''): array
166 foreach ($timelines as $tab) {
167 if (is_null($tab->path) && !empty($parameter)) {
168 $path = $prefix . '?' . http_build_query([$parameter => $tab->code]);
170 $path = $tab->path ?? $prefix . '/' . $tab->code;
172 $tabs[$tab->code] = [
173 'label' => $tab->label,
175 'sel' => $this->selectedTab == $tab->code ? 'active' : '',
176 'title' => $tab->description,
177 'id' => $prefix . '-' . $tab->code . '-tab',
178 'accesskey' => $tab->accessKey,
185 * Database query for the channel page
190 protected function getChannelItems()
192 $uid = $this->session->getLocalUserId();
194 if ($this->selectedTab == TimelineEntity::WHATSHOT) {
195 if (!is_null($this->accountType)) {
196 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` = ?", $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), $this->accountType];
198 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` != ?", $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), Contact::TYPE_COMMUNITY];
200 } elseif ($this->selectedTab == TimelineEntity::FORYOU) {
201 $cid = Contact::getPublicIdByUserId($uid);
204 "(`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `relation-thread-score` > ?) OR
205 ((`comments` >= ? OR `activities` >= ?) AND `owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ?)) OR
206 (`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` IN (?, ?) AND `notify_new_posts`)))",
207 $cid, $this->getMedianRelationThreadScore($cid, 4), $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), $cid,
208 $uid, Contact::FRIEND, Contact::SHARING
210 } elseif ($this->selectedTab == TimelineEntity::FOLLOWERS) {
211 $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` = ?)", $uid, Contact::FOLLOWER];
212 } elseif ($this->selectedTab == TimelineEntity::SHARERSOFSHARERS) {
213 $cid = Contact::getPublicIdByUserId($uid);
215 // @todo Suggest posts from contacts that are followed most by our followers
217 "`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `last-interaction` > ?
218 AND `relation-cid` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ? AND `relation-thread-score` >= ?)
219 AND NOT `cid` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ?))",
220 DateTimeFormat::utc('now - ' . $this->config->get('channel', 'sharer_interaction_days') . ' day'), $cid, $this->getMedianRelationThreadScore($cid, 4), $cid
222 } elseif ($this->selectedTab == TimelineEntity::IMAGE) {
223 $condition = ["`media-type` & ?", 1];
224 } elseif ($this->selectedTab == TimelineEntity::VIDEO) {
225 $condition = ["`media-type` & ?", 2];
226 } elseif ($this->selectedTab == TimelineEntity::AUDIO) {
227 $condition = ["`media-type` & ?", 4];
228 } elseif ($this->selectedTab == TimelineEntity::LANGUAGE) {
229 $condition = ["JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?", $this->l10n->convertCodeForLanguageDetection(User::getLanguageCode($uid))];
232 if ($this->selectedTab != TimelineEntity::LANGUAGE) {
233 $condition = $this->addLanguageCondition($uid, $condition);
236 $condition = DBA::mergeConditions($condition, ["NOT EXISTS(SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `post-engagement`.`owner-id` AND (`ignored` OR `blocked` OR `collapsed`))", $uid]);
238 if (($this->selectedTab != TimelineEntity::WHATSHOT) && !is_null($this->accountType)) {
239 $condition = DBA::mergeConditions($condition, ['contact-type' => $this->accountType]);
242 $params = ['order' => ['created' => true], 'limit' => $this->itemsPerPage];
244 if (!empty($this->itemUriId)) {
245 $condition = DBA::mergeConditions($condition, ['uri-id' => $this->itemUriId]);
247 if ($this->noSharer) {
248 $condition = DBA::mergeConditions($condition, ["NOT `uri-id` IN (SELECT `uri-id` FROM `post-user` WHERE `post-user`.`uid` = ? AND `post-user`.`uri-id` = `post-engagement`.`uri-id`)", $this->session->getLocalUserId()]);
251 if (isset($this->maxId)) {
252 $condition = DBA::mergeConditions($condition, ["`created` < ?", $this->maxId]);
255 if (isset($this->minId)) {
256 $condition = DBA::mergeConditions($condition, ["`created` > ?", $this->minId]);
258 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
259 if (!isset($this->maxId)) {
260 $params['order']['created'] = false;
265 $items = $this->database->selectToArray('post-engagement', ['uri-id', 'created'], $condition, $params);
270 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
271 if (empty($this->itemUriId) && isset($this->minId) && !isset($this->maxId)) {
272 $items = array_reverse($items);
275 $condition = ['unseen' => true, 'uid' => $uid, 'parent-uri-id' => array_column($items, 'uri-id')];
276 $this->setItemsSeenByCondition($condition);
281 private function addLanguageCondition(int $uid, array $condition): array
284 $languages = $this->pConfig->get($uid, 'channel', 'languages', [User::getLanguageCode($uid)]);
285 $languages = $this->l10n->convertForLanguageDetection($languages);
286 foreach ($languages as $language) {
287 $conditions[] = "JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?";
288 $condition[] = $language;
290 if (!empty($conditions)) {
291 $condition[0] .= " AND (`language` IS NULL OR " . implode(' OR ', $conditions) . ")";
296 private function getMedianComments(int $uid, int $divider): int
298 $languages = $this->pConfig->get($uid, 'channel', 'languages', [User::getLanguageCode($uid)]);
299 $cache_key = 'Channel:getMedianComments:' . $divider . ':' . implode(':', $languages);
300 $comments = $this->cache->get($cache_key);
301 if (!empty($comments)) {
305 $condition = ["`contact-type` != ? AND `comments` > ?", Contact::TYPE_COMMUNITY, 0];
306 $condition = $this->addLanguageCondition($uid, $condition);
308 $limit = $this->database->count('post-engagement', $condition) / $divider;
309 $post = $this->database->selectToArray('post-engagement', ['comments'], $condition, ['order' => ['comments' => true], 'limit' => [$limit, 1]]);
310 $comments = $post[0]['comments'] ?? 0;
311 if (empty($comments)) {
315 $this->cache->set($cache_key, $comments, Duration::HALF_HOUR);
316 $this->logger->debug('Calculated median comments', ['divider' => $divider, 'languages' => $languages, 'median' => $comments]);
320 private function getMedianActivities(int $uid, int $divider): int
322 $languages = $this->pConfig->get($uid, 'channel', 'languages', [User::getLanguageCode($uid)]);
323 $cache_key = 'Channel:getMedianActivities:' . $divider . ':' . implode(':', $languages);
324 $activities = $this->cache->get($cache_key);
325 if (!empty($activities)) {
329 $condition = ["`contact-type` != ? AND `activities` > ?", Contact::TYPE_COMMUNITY, 0];
330 $condition = $this->addLanguageCondition($uid, $condition);
332 $limit = $this->database->count('post-engagement', $condition) / $divider;
333 $post = $this->database->selectToArray('post-engagement', ['activities'], $condition, ['order' => ['activities' => true], 'limit' => [$limit, 1]]);
334 $activities = $post[0]['activities'] ?? 0;
335 if (empty($activities)) {
339 $this->cache->set($cache_key, $activities, Duration::HALF_HOUR);
340 $this->logger->debug('Calculated median activities', ['divider' => $divider, 'languages' => $languages, 'median' => $activities]);
344 private function getMedianRelationThreadScore(int $cid, int $divider): int
346 $cache_key = 'Channel:getThreadScore:' . $cid . ':' . $divider;
347 $score = $this->cache->get($cache_key);
348 if (!empty($score)) {
352 $condition = ["`relation-cid` = ? AND `relation-thread-score` > ?", $cid, 0];
354 $limit = $this->database->count('contact-relation', $condition) / $divider;
355 $relation = $this->database->selectToArray('contact-relation', ['relation-thread-score'], $condition, ['order' => ['relation-thread-score' => true], 'limit' => [$limit, 1]]);
356 $score = $relation[0]['relation-thread-score'] ?? 0;
361 $this->cache->set($cache_key, $score, Duration::HALF_HOUR);
362 $this->logger->debug('Calculated median score', ['cid' => $cid, 'divider' => $divider, 'median' => $score]);
367 * Computes the displayed items.
369 * Community pages have a restriction on how many successive posts by the same author can show on any given page,
370 * so we may have to retrieve more content beyond the first query
375 protected function getCommunityItems()
377 $items = $this->selectItems();
379 $maxpostperauthor = (int) $this->config->get('system', 'max_author_posts_community_page');
380 if ($maxpostperauthor != 0 && $this->selectedTab == 'local') {
382 $previousauthor = '';
384 $selected_items = [];
386 while (count($selected_items) < $this->itemsPerPage && ++$count < 50 && count($items) > 0) {
387 foreach ($items as $item) {
388 if ($previousauthor == $item["author-link"]) {
393 $previousauthor = $item["author-link"];
395 if (($numposts < $maxpostperauthor) && (count($selected_items) < $this->itemsPerPage)) {
396 $selected_items[] = $item;
400 // If we're looking at a "previous page", the lookup continues forward in time because the list is
401 // sorted in chronologically decreasing order
402 if (isset($this->minId)) {
403 $this->minId = $items[0]['commented'];
405 // In any other case, the lookup continues backwards in time
406 $this->maxId = $items[count($items) - 1]['commented'];
409 $items = $this->selectItems();
412 $selected_items = $items;
415 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => array_column($selected_items, 'uri-id')];
416 $this->setItemsSeenByCondition($condition);
418 return $selected_items;
422 * Database query for the community page
426 * @TODO Move to repository/factory
428 private function selectItems()
430 if ($this->selectedTab == 'local') {
431 if (!is_null($this->accountType)) {
432 $condition = ["`wall` AND `origin` AND `private` = ? AND `owner-contact-type` = ?", Item::PUBLIC, $this->accountType];
434 $condition = ["`wall` AND `origin` AND `private` = ?", Item::PUBLIC];
436 } elseif ($this->selectedTab == 'global') {
437 if (!is_null($this->accountType)) {
438 $condition = ["`uid` = ? AND `private` = ? AND `owner-contact-type` = ?", 0, Item::PUBLIC, $this->accountType];
440 $condition = ["`uid` = ? AND `private` = ?", 0, Item::PUBLIC];
446 $params = ['order' => ['commented' => true], 'limit' => $this->itemsPerPage];
448 if (!empty($this->itemUriId)) {
449 $condition = DBA::mergeConditions($condition, ['uri-id' => $this->itemUriId]);
451 if ($this->session->getLocalUserId() && $this->noSharer) {
452 $condition = DBA::mergeConditions($condition, ["NOT `uri-id` IN (SELECT `uri-id` FROM `post-user` WHERE `post-user`.`uid` = ? AND `post-user`.`uri-id` = `post-thread-user-view`.`uri-id`)", $this->session->getLocalUserId()]);
455 if (isset($this->maxId)) {
456 $condition = DBA::mergeConditions($condition, ["`commented` < ?", $this->maxId]);
459 if (isset($this->minId)) {
460 $condition = DBA::mergeConditions($condition, ["`commented` > ?", $this->minId]);
462 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
463 if (!isset($this->maxId)) {
464 $params['order']['commented'] = false;
469 $r = Post::selectThreadForUser($this->session->getLocalUserId() ?: 0, ['uri-id', 'commented', 'author-link'], $condition, $params);
471 $items = Post::toArray($r);
476 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
477 if (empty($this->itemUriId) && isset($this->minId) && !isset($this->maxId)) {
478 $items = array_reverse($items);
487 * @param array $condition The array with the SQL condition
488 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
490 protected function setItemsSeenByCondition(array $condition)
492 if (empty($condition)) {
496 $unseen = Post::exists($condition);
499 /// @todo handle huge "unseen" updates in the background to avoid timeout errors
500 Item::update(['unseen' => false], $condition);