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;
70 /** @var App\Mode $mode */
72 /** @var IHandleUserSessions */
76 /** @var IManagePersonalConfigValues */
78 /** @var IManageConfigValues The config */
83 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 = [])
85 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
88 $this->session = $session;
89 $this->database = $database;
90 $this->pConfig = $pConfig;
91 $this->config = $config;
92 $this->cache = $cache;
96 * Computes module parameters from the request and local configuration
98 * @throws HTTPException\BadRequestException
99 * @throws HTTPException\ForbiddenException
101 protected function parseRequest(array $request)
103 $this->logger->debug('Got request', $request);
104 $this->selectedTab = $this->parameters['content'] ?? $request['channel'] ?? '';
106 $this->accountTypeString = $request['accounttype'] ?? $this->parameters['accounttype'] ?? '';
107 $this->accountType = User::getAccountTypeByString($this->accountTypeString);
109 if ($this->mode->isMobile()) {
110 $this->itemsPerPage = $this->pConfig->get(
111 $this->session->getLocalUserId(),
113 'itemspage_mobile_network',
114 $this->config->get('system', 'itemspage_network_mobile')
117 $this->itemsPerPage = $this->pConfig->get(
118 $this->session->getLocalUserId(),
121 $this->config->get('system', 'itemspage_network')
125 if (!empty($request['item'])) {
126 $item = Post::selectFirst(['parent', 'parent-uri-id'], ['id' => $request['item']]);
127 $this->itemUriId = $item['parent-uri-id'] ?? 0;
129 $this->itemUriId = 0;
132 $this->minId = $request['min_id'] ?? null;
133 $this->maxId = $request['max_id'] ?? null;
135 $this->noSharer = !empty($request['no_sharer']);
136 $this->force = !empty($request['force']) && !empty($request['item']);
137 $this->update = !empty($request['force']) && !empty($request['first_received']) && !empty($request['first_created']) && !empty($request['first_uriid']) && !empty($request['first_commented']);
140 protected function getNoSharerWidget(string $base): string
142 $path = $this->selectedTab;
143 if (!empty($this->accountTypeString)) {
144 $path .= '/' . $this->accountTypeString;
146 $query_parameters = [];
148 if (!empty($this->minId)) {
149 $query_parameters['min_id'] = $this->minId;
151 if (!empty($this->maxId)) {
152 $query_parameters['max_id'] = $this->maxId;
155 $path_all = $path . (!empty($query_parameters) ? '?' . http_build_query($query_parameters) : '');
156 $path_no_sharer = $path . '?' . http_build_query(array_merge($query_parameters, ['no_sharer' => true]));
157 return Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/community_sharer.tpl'), [
158 '$title' => $this->l10n->t('Own Contacts'),
159 '$path_all' => $path_all,
160 '$path_no_sharer' => $path_no_sharer,
161 '$no_sharer' => $this->noSharer,
162 '$all' => $this->l10n->t('Include'),
163 '$no_sharer_label' => $this->l10n->t('Hide'),
168 protected function getTabArray(Timelines $timelines, string $prefix, string $parameter = ''): array
172 foreach ($timelines as $tab) {
173 if (is_null($tab->path) && !empty($parameter)) {
174 $path = $prefix . '?' . http_build_query([$parameter => $tab->code]);
176 $path = $tab->path ?? $prefix . '/' . $tab->code;
178 $tabs[$tab->code] = [
179 'label' => $tab->label,
181 'sel' => $this->selectedTab == $tab->code ? 'active' : '',
182 'title' => $tab->description,
183 'id' => $prefix . '-' . $tab->code . '-tab',
184 'accesskey' => $tab->accessKey,
191 * Database query for the channel page
196 protected function getChannelItems()
198 $items = $this->getRawChannelItems();
200 $contacts = $this->database->selectToArray('user-contact', ['cid'], ['channel-frequency' => Contact\User::FREQUENCY_REDUCED, 'cid' => array_column($items, 'owner-id')]);
201 $reduced = array_column($contacts, 'cid');
203 $maxpostperauthor = $this->config->get('channel', 'max_posts_per_author');
205 if ($maxpostperauthor != 0) {
208 $selected_items = [];
210 while (count($selected_items) < $this->itemsPerPage && ++$count < 50 && count($items) > 0) {
211 $maxposts = round((count($items) / $this->itemsPerPage) * $maxpostperauthor);
212 $minId = $items[array_key_first($items)]['created'];
213 $maxId = $items[array_key_last($items)]['created'];
215 foreach ($items as $item) {
216 if (!in_array($item['owner-id'], $reduced)) {
219 $owner_posts[$item['owner-id']][$item['uri-id']] = (($item['comments'] * 100) + $item['activities']);
221 foreach ($owner_posts as $posts) {
222 if (count($posts) <= $maxposts) {
226 while (count($posts) > $maxposts) {
227 $uri_id = array_key_first($posts);
228 unset($posts[$uri_id]);
229 unset($items[$uri_id]);
232 $selected_items = array_merge($selected_items, $items);
234 // If we're looking at a "previous page", the lookup continues forward in time because the list is
235 // sorted in chronologically decreasing order
236 if (!empty($this->minId)) {
237 $this->minId = $minId;
239 // In any other case, the lookup continues backwards in time
240 $this->maxId = $maxId;
243 if (count($selected_items) < $this->itemsPerPage) {
244 $items = $this->getRawChannelItems();
248 $selected_items = $items;
251 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => array_column($selected_items, 'uri-id')];
252 $this->setItemsSeenByCondition($condition);
254 return $selected_items;
258 * Database query for the channel page
263 private function getRawChannelItems()
265 $uid = $this->session->getLocalUserId();
267 if ($this->selectedTab == TimelineEntity::WHATSHOT) {
268 if (!is_null($this->accountType)) {
269 $condition = ["(`comments` > ? OR `activities` > ?) AND `contact-type` = ?", $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), $this->accountType];
271 $condition = ["(`comments` > ? OR `activities` > ?) AND `contact-type` != ?", $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), Contact::TYPE_COMMUNITY];
273 } elseif ($this->selectedTab == TimelineEntity::FORYOU) {
274 $cid = Contact::getPublicIdByUserId($uid);
277 "(`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `relation-thread-score` > ?) OR
278 ((`comments` >= ? OR `activities` >= ?) AND `owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ?)) OR
279 (`owner-id` IN (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND (`notify_new_posts` OR `channel-frequency` = ?))))",
280 $cid, $this->getMedianRelationThreadScore($cid, 4), $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), $cid,
281 $uid, Contact\User::FREQUENCY_ALWAYS
283 } elseif ($this->selectedTab == TimelineEntity::FOLLOWERS) {
284 $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` = ?)", $uid, Contact::FOLLOWER];
285 } elseif ($this->selectedTab == TimelineEntity::SHARERSOFSHARERS) {
286 $cid = Contact::getPublicIdByUserId($uid);
288 // @todo Suggest posts from contacts that are followed most by our followers
290 "`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `last-interaction` > ?
291 AND `relation-cid` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ? AND `relation-thread-score` >= ?)
292 AND NOT `cid` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ?))",
293 DateTimeFormat::utc('now - ' . $this->config->get('channel', 'sharer_interaction_days') . ' day'), $cid, $this->getMedianRelationThreadScore($cid, 4), $cid
295 } elseif ($this->selectedTab == TimelineEntity::IMAGE) {
296 $condition = ["`media-type` & ?", 1];
297 } elseif ($this->selectedTab == TimelineEntity::VIDEO) {
298 $condition = ["`media-type` & ?", 2];
299 } elseif ($this->selectedTab == TimelineEntity::AUDIO) {
300 $condition = ["`media-type` & ?", 4];
301 } elseif ($this->selectedTab == TimelineEntity::LANGUAGE) {
302 $condition = ["JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?", $this->l10n->convertCodeForLanguageDetection(User::getLanguageCode($uid))];
305 if ($this->selectedTab != TimelineEntity::LANGUAGE) {
306 $condition = $this->addLanguageCondition($uid, $condition);
309 $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` OR `is-blocked` OR `channel-frequency` = ?))", $uid, Contact\User::FREQUENCY_NEVER]);
311 if (($this->selectedTab != TimelineEntity::WHATSHOT) && !is_null($this->accountType)) {
312 $condition = DBA::mergeConditions($condition, ['contact-type' => $this->accountType]);
315 $params = ['order' => ['created' => true], 'limit' => $this->itemsPerPage];
317 if (!empty($this->itemUriId)) {
318 $condition = DBA::mergeConditions($condition, ['uri-id' => $this->itemUriId]);
320 if ($this->noSharer) {
321 $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()]);
324 if (isset($this->maxId)) {
325 $condition = DBA::mergeConditions($condition, ["`created` < ?", $this->maxId]);
328 if (isset($this->minId)) {
329 $condition = DBA::mergeConditions($condition, ["`created` > ?", $this->minId]);
331 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
332 if (!isset($this->maxId)) {
333 $params['order']['created'] = false;
339 $result = $this->database->select('post-engagement', ['uri-id', 'created', 'owner-id', 'comments', 'activities'], $condition, $params);
340 while ($item = $this->database->fetch($result)) {
341 $items[$item['uri-id']] = $item;
343 $this->database->close($result);
349 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
350 if (empty($this->itemUriId) && isset($this->minId) && !isset($this->maxId)) {
351 $items = array_reverse($items, true);
354 $condition = ['unseen' => true, 'uid' => $uid, 'parent-uri-id' => array_column($items, 'uri-id')];
355 $this->setItemsSeenByCondition($condition);
360 private function addLanguageCondition(int $uid, array $condition): array
363 $languages = $this->pConfig->get($uid, 'channel', 'languages', [User::getLanguageCode($uid)]);
364 $languages = $this->l10n->convertForLanguageDetection($languages);
365 foreach ($languages as $language) {
366 $conditions[] = "JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?";
367 $condition[] = $language;
369 if (!empty($conditions)) {
370 $condition[0] .= " AND (`language` IS NULL OR " . implode(' OR ', $conditions) . ")";
375 private function getMedianComments(int $uid, int $divider): int
377 $languages = $this->pConfig->get($uid, 'channel', 'languages', [User::getLanguageCode($uid)]);
378 $cache_key = 'Channel:getMedianComments:' . $divider . ':' . implode(':', $languages);
379 $comments = $this->cache->get($cache_key);
380 if (!empty($comments)) {
384 $condition = ["`contact-type` != ? AND `comments` > ?", Contact::TYPE_COMMUNITY, 0];
385 $condition = $this->addLanguageCondition($uid, $condition);
387 $limit = $this->database->count('post-engagement', $condition) / $divider;
388 $post = $this->database->selectToArray('post-engagement', ['comments'], $condition, ['order' => ['comments' => true], 'limit' => [$limit, 1]]);
389 $comments = $post[0]['comments'] ?? 0;
390 if (empty($comments)) {
394 $this->cache->set($cache_key, $comments, Duration::HALF_HOUR);
395 $this->logger->debug('Calculated median comments', ['divider' => $divider, 'languages' => $languages, 'median' => $comments]);
399 private function getMedianActivities(int $uid, int $divider): int
401 $languages = $this->pConfig->get($uid, 'channel', 'languages', [User::getLanguageCode($uid)]);
402 $cache_key = 'Channel:getMedianActivities:' . $divider . ':' . implode(':', $languages);
403 $activities = $this->cache->get($cache_key);
404 if (!empty($activities)) {
408 $condition = ["`contact-type` != ? AND `activities` > ?", Contact::TYPE_COMMUNITY, 0];
409 $condition = $this->addLanguageCondition($uid, $condition);
411 $limit = $this->database->count('post-engagement', $condition) / $divider;
412 $post = $this->database->selectToArray('post-engagement', ['activities'], $condition, ['order' => ['activities' => true], 'limit' => [$limit, 1]]);
413 $activities = $post[0]['activities'] ?? 0;
414 if (empty($activities)) {
418 $this->cache->set($cache_key, $activities, Duration::HALF_HOUR);
419 $this->logger->debug('Calculated median activities', ['divider' => $divider, 'languages' => $languages, 'median' => $activities]);
423 private function getMedianRelationThreadScore(int $cid, int $divider): int
425 $cache_key = 'Channel:getThreadScore:' . $cid . ':' . $divider;
426 $score = $this->cache->get($cache_key);
427 if (!empty($score)) {
431 $condition = ["`relation-cid` = ? AND `relation-thread-score` > ?", $cid, 0];
433 $limit = $this->database->count('contact-relation', $condition) / $divider;
434 $relation = $this->database->selectToArray('contact-relation', ['relation-thread-score'], $condition, ['order' => ['relation-thread-score' => true], 'limit' => [$limit, 1]]);
435 $score = $relation[0]['relation-thread-score'] ?? 0;
440 $this->cache->set($cache_key, $score, Duration::HALF_HOUR);
441 $this->logger->debug('Calculated median score', ['cid' => $cid, 'divider' => $divider, 'median' => $score]);
446 * Computes the displayed items.
448 * Community pages have a restriction on how many successive posts by the same author can show on any given page,
449 * so we may have to retrieve more content beyond the first query
454 protected function getCommunityItems()
456 $items = $this->selectItems();
458 $maxpostperauthor = (int) $this->config->get('system', 'max_author_posts_community_page');
459 if ($maxpostperauthor != 0 && $this->selectedTab == 'local') {
461 $previousauthor = '';
463 $selected_items = [];
465 while (count($selected_items) < $this->itemsPerPage && ++$count < 50 && count($items) > 0) {
466 foreach ($items as $item) {
467 if ($previousauthor == $item["author-link"]) {
472 $previousauthor = $item["author-link"];
474 if (($numposts < $maxpostperauthor) && (count($selected_items) < $this->itemsPerPage)) {
475 $selected_items[] = $item;
479 // If we're looking at a "previous page", the lookup continues forward in time because the list is
480 // sorted in chronologically decreasing order
481 if (isset($this->minId)) {
482 $this->minId = $items[0]['received'];
484 // In any other case, the lookup continues backwards in time
485 $this->maxId = $items[count($items) - 1]['received'];
488 $items = $this->selectItems();
491 $selected_items = $items;
494 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => array_column($selected_items, 'uri-id')];
495 $this->setItemsSeenByCondition($condition);
497 return $selected_items;
501 * Database query for the community page
505 * @TODO Move to repository/factory
507 private function selectItems()
509 if ($this->selectedTab == 'local') {
510 $condition = ["`wall` AND `origin` AND `private` = ?", Item::PUBLIC];
511 } elseif ($this->selectedTab == 'global') {
512 $condition = ["`uid` = ? AND `private` = ?", 0, Item::PUBLIC];
517 if (!is_null($this->accountType)) {
518 $condition = DBA::mergeConditions($condition, ['owner-contact-type' => $this->accountType]);
521 $params = ['order' => ['received' => true], 'limit' => $this->itemsPerPage];
523 if (!empty($this->itemUriId)) {
524 $condition = DBA::mergeConditions($condition, ['uri-id' => $this->itemUriId]);
526 if ($this->session->getLocalUserId() && $this->noSharer) {
527 $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()]);
530 if (isset($this->maxId)) {
531 $condition = DBA::mergeConditions($condition, ["`received` < ?", $this->maxId]);
534 if (isset($this->minId)) {
535 $condition = DBA::mergeConditions($condition, ["`received` > ?", $this->minId]);
537 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
538 if (!isset($this->maxId)) {
539 $params['order']['received'] = false;
544 $r = Post::selectThreadForUser($this->session->getLocalUserId() ?: 0, ['uri-id', 'received', 'author-link'], $condition, $params);
546 $items = Post::toArray($r);
551 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
552 if (empty($this->itemUriId) && isset($this->minId) && !isset($this->maxId)) {
553 $items = array_reverse($items);
562 * @param array $condition The array with the SQL condition
563 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
565 protected function setItemsSeenByCondition(array $condition)
567 if (empty($condition)) {
571 $unseen = Post::exists($condition);
574 /// @todo handle huge "unseen" updates in the background to avoid timeout errors
575 Item::update(['unseen' => false], $condition);