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;
68 /** @var App\Mode $mode */
70 /** @var IHandleUserSessions */
74 /** @var IManagePersonalConfigValues */
76 /** @var IManageConfigValues The config */
81 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 = [])
83 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
86 $this->session = $session;
87 $this->database = $database;
88 $this->pConfig = $pConfig;
89 $this->config = $config;
90 $this->cache = $cache;
94 * Computes module parameters from the request and local configuration
96 * @throws HTTPException\BadRequestException
97 * @throws HTTPException\ForbiddenException
99 protected function parseRequest(array $request)
101 $this->logger->debug('Got request', $request);
102 $this->selectedTab = $this->parameters['content'] ?? $request['channel'] ?? '';
104 $this->accountTypeString = $request['accounttype'] ?? $this->parameters['accounttype'] ?? '';
105 $this->accountType = User::getAccountTypeByString($this->accountTypeString);
107 if ($this->mode->isMobile()) {
108 $this->itemsPerPage = $this->pConfig->get(
109 $this->session->getLocalUserId(),
111 'itemspage_mobile_network',
112 $this->config->get('system', 'itemspage_network_mobile')
115 $this->itemsPerPage = $this->pConfig->get(
116 $this->session->getLocalUserId(),
119 $this->config->get('system', 'itemspage_network')
123 if (!empty($request['item'])) {
124 $item = Post::selectFirst(['parent', 'parent-uri-id'], ['id' => $request['item']]);
125 $this->itemUriId = $item['parent-uri-id'] ?? 0;
127 $this->itemUriId = 0;
130 $this->minId = $request['min_id'] ?? null;
131 $this->maxId = $request['max_id'] ?? null;
133 $this->noSharer = !empty($request['no_sharer']);
134 $this->force = !empty($request['force']);
137 protected function getNoSharerWidget(string $base): string
139 $path = $this->selectedTab;
140 if (!empty($this->accountTypeString)) {
141 $path .= '/' . $this->accountTypeString;
143 $query_parameters = [];
145 if (!empty($this->minId)) {
146 $query_parameters['min_id'] = $this->minId;
148 if (!empty($this->maxId)) {
149 $query_parameters['max_id'] = $this->maxId;
152 $path_all = $path . (!empty($query_parameters) ? '?' . http_build_query($query_parameters) : '');
153 $path_no_sharer = $path . '?' . http_build_query(array_merge($query_parameters, ['no_sharer' => true]));
154 return Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/community_sharer.tpl'), [
155 '$title' => $this->l10n->t('Own Contacts'),
156 '$path_all' => $path_all,
157 '$path_no_sharer' => $path_no_sharer,
158 '$no_sharer' => $this->noSharer,
159 '$all' => $this->l10n->t('Include'),
160 '$no_sharer_label' => $this->l10n->t('Hide'),
165 protected function getTabArray(Timelines $timelines, string $prefix, string $parameter = ''): array
169 foreach ($timelines as $tab) {
170 if (is_null($tab->path) && !empty($parameter)) {
171 $path = $prefix . '?' . http_build_query([$parameter => $tab->code]);
173 $path = $tab->path ?? $prefix . '/' . $tab->code;
175 $tabs[$tab->code] = [
176 'label' => $tab->label,
178 'sel' => $this->selectedTab == $tab->code ? 'active' : '',
179 'title' => $tab->description,
180 'id' => $prefix . '-' . $tab->code . '-tab',
181 'accesskey' => $tab->accessKey,
188 * Database query for the channel page
193 protected function getChannelItems()
195 $items = $this->getRawChannelItems();
197 $contacts = $this->database->selectToArray('user-contact', ['cid'], ['channel-frequency' => Contact\User::FREQUENCY_REDUCED, 'cid' => array_column($items, 'owner-id')]);
198 $reduced = array_column($contacts, 'cid');
200 $maxpostperauthor = $this->config->get('channel', 'max_posts_per_author');
202 if ($maxpostperauthor != 0) {
205 $selected_items = [];
207 while (count($selected_items) < $this->itemsPerPage && ++$count < 50 && count($items) > 0) {
208 $maxposts = round((count($items) / $this->itemsPerPage) * $maxpostperauthor);
209 $minId = $items[array_key_first($items)]['created'];
210 $maxId = $items[array_key_last($items)]['created'];
212 foreach ($items as $item) {
213 if (!in_array($item['owner-id'], $reduced)) {
216 $owner_posts[$item['owner-id']][$item['uri-id']] = (($item['comments'] * 100) + $item['activities']);
218 foreach ($owner_posts as $posts) {
219 if (count($posts) <= $maxposts) {
223 while (count($posts) > $maxposts) {
224 $uri_id = array_key_first($posts);
225 unset($posts[$uri_id]);
226 unset($items[$uri_id]);
229 $selected_items = array_merge($selected_items, $items);
231 // If we're looking at a "previous page", the lookup continues forward in time because the list is
232 // sorted in chronologically decreasing order
233 if (!empty($this->minId)) {
234 $this->minId = $minId;
236 // In any other case, the lookup continues backwards in time
237 $this->maxId = $maxId;
240 if (count($selected_items) < $this->itemsPerPage) {
241 $items = $this->getRawChannelItems();
245 $selected_items = $items;
248 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => array_column($selected_items, 'uri-id')];
249 $this->setItemsSeenByCondition($condition);
251 return $selected_items;
255 * Database query for the channel page
260 private function getRawChannelItems()
262 $uid = $this->session->getLocalUserId();
264 if ($this->selectedTab == TimelineEntity::WHATSHOT) {
265 if (!is_null($this->accountType)) {
266 $condition = ["(`comments` > ? OR `activities` > ?) AND `contact-type` = ?", $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), $this->accountType];
268 $condition = ["(`comments` > ? OR `activities` > ?) AND `contact-type` != ?", $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), Contact::TYPE_COMMUNITY];
270 } elseif ($this->selectedTab == TimelineEntity::FORYOU) {
271 $cid = Contact::getPublicIdByUserId($uid);
274 "(`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `relation-thread-score` > ?) OR
275 ((`comments` >= ? OR `activities` >= ?) AND `owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ?)) OR
276 (`owner-id` IN (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND (`notify_new_posts` OR `channel-frequency` = ?))))",
277 $cid, $this->getMedianRelationThreadScore($cid, 4), $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), $cid,
278 $uid, Contact\User::FREQUENCY_ALWAYS
280 } elseif ($this->selectedTab == TimelineEntity::FOLLOWERS) {
281 $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` = ?)", $uid, Contact::FOLLOWER];
282 } elseif ($this->selectedTab == TimelineEntity::SHARERSOFSHARERS) {
283 $cid = Contact::getPublicIdByUserId($uid);
285 // @todo Suggest posts from contacts that are followed most by our followers
287 "`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `last-interaction` > ?
288 AND `relation-cid` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ? AND `relation-thread-score` >= ?)
289 AND NOT `cid` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ?))",
290 DateTimeFormat::utc('now - ' . $this->config->get('channel', 'sharer_interaction_days') . ' day'), $cid, $this->getMedianRelationThreadScore($cid, 4), $cid
292 } elseif ($this->selectedTab == TimelineEntity::IMAGE) {
293 $condition = ["`media-type` & ?", 1];
294 } elseif ($this->selectedTab == TimelineEntity::VIDEO) {
295 $condition = ["`media-type` & ?", 2];
296 } elseif ($this->selectedTab == TimelineEntity::AUDIO) {
297 $condition = ["`media-type` & ?", 4];
298 } elseif ($this->selectedTab == TimelineEntity::LANGUAGE) {
299 $condition = ["JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?", $this->l10n->convertCodeForLanguageDetection(User::getLanguageCode($uid))];
302 if ($this->selectedTab != TimelineEntity::LANGUAGE) {
303 $condition = $this->addLanguageCondition($uid, $condition);
306 $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]);
308 if (($this->selectedTab != TimelineEntity::WHATSHOT) && !is_null($this->accountType)) {
309 $condition = DBA::mergeConditions($condition, ['contact-type' => $this->accountType]);
312 $params = ['order' => ['created' => true], 'limit' => $this->itemsPerPage];
314 if (!empty($this->itemUriId)) {
315 $condition = DBA::mergeConditions($condition, ['uri-id' => $this->itemUriId]);
317 if ($this->noSharer) {
318 $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()]);
321 if (isset($this->maxId)) {
322 $condition = DBA::mergeConditions($condition, ["`created` < ?", $this->maxId]);
325 if (isset($this->minId)) {
326 $condition = DBA::mergeConditions($condition, ["`created` > ?", $this->minId]);
328 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
329 if (!isset($this->maxId)) {
330 $params['order']['created'] = false;
336 $result = $this->database->select('post-engagement', ['uri-id', 'created', 'owner-id', 'comments', 'activities'], $condition, $params);
337 while ($item = $this->database->fetch($result)) {
338 $items[$item['uri-id']] = $item;
340 $this->database->close($result);
346 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
347 if (empty($this->itemUriId) && isset($this->minId) && !isset($this->maxId)) {
348 $items = array_reverse($items, true);
351 $condition = ['unseen' => true, 'uid' => $uid, 'parent-uri-id' => array_column($items, 'uri-id')];
352 $this->setItemsSeenByCondition($condition);
357 private function addLanguageCondition(int $uid, array $condition): array
360 $languages = $this->pConfig->get($uid, 'channel', 'languages', [User::getLanguageCode($uid)]);
361 $languages = $this->l10n->convertForLanguageDetection($languages);
362 foreach ($languages as $language) {
363 $conditions[] = "JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?";
364 $condition[] = $language;
366 if (!empty($conditions)) {
367 $condition[0] .= " AND (`language` IS NULL OR " . implode(' OR ', $conditions) . ")";
372 private function getMedianComments(int $uid, int $divider): int
374 $languages = $this->pConfig->get($uid, 'channel', 'languages', [User::getLanguageCode($uid)]);
375 $cache_key = 'Channel:getMedianComments:' . $divider . ':' . implode(':', $languages);
376 $comments = $this->cache->get($cache_key);
377 if (!empty($comments)) {
381 $condition = ["`contact-type` != ? AND `comments` > ?", Contact::TYPE_COMMUNITY, 0];
382 $condition = $this->addLanguageCondition($uid, $condition);
384 $limit = $this->database->count('post-engagement', $condition) / $divider;
385 $post = $this->database->selectToArray('post-engagement', ['comments'], $condition, ['order' => ['comments' => true], 'limit' => [$limit, 1]]);
386 $comments = $post[0]['comments'] ?? 0;
387 if (empty($comments)) {
391 $this->cache->set($cache_key, $comments, Duration::HALF_HOUR);
392 $this->logger->debug('Calculated median comments', ['divider' => $divider, 'languages' => $languages, 'median' => $comments]);
396 private function getMedianActivities(int $uid, int $divider): int
398 $languages = $this->pConfig->get($uid, 'channel', 'languages', [User::getLanguageCode($uid)]);
399 $cache_key = 'Channel:getMedianActivities:' . $divider . ':' . implode(':', $languages);
400 $activities = $this->cache->get($cache_key);
401 if (!empty($activities)) {
405 $condition = ["`contact-type` != ? AND `activities` > ?", Contact::TYPE_COMMUNITY, 0];
406 $condition = $this->addLanguageCondition($uid, $condition);
408 $limit = $this->database->count('post-engagement', $condition) / $divider;
409 $post = $this->database->selectToArray('post-engagement', ['activities'], $condition, ['order' => ['activities' => true], 'limit' => [$limit, 1]]);
410 $activities = $post[0]['activities'] ?? 0;
411 if (empty($activities)) {
415 $this->cache->set($cache_key, $activities, Duration::HALF_HOUR);
416 $this->logger->debug('Calculated median activities', ['divider' => $divider, 'languages' => $languages, 'median' => $activities]);
420 private function getMedianRelationThreadScore(int $cid, int $divider): int
422 $cache_key = 'Channel:getThreadScore:' . $cid . ':' . $divider;
423 $score = $this->cache->get($cache_key);
424 if (!empty($score)) {
428 $condition = ["`relation-cid` = ? AND `relation-thread-score` > ?", $cid, 0];
430 $limit = $this->database->count('contact-relation', $condition) / $divider;
431 $relation = $this->database->selectToArray('contact-relation', ['relation-thread-score'], $condition, ['order' => ['relation-thread-score' => true], 'limit' => [$limit, 1]]);
432 $score = $relation[0]['relation-thread-score'] ?? 0;
437 $this->cache->set($cache_key, $score, Duration::HALF_HOUR);
438 $this->logger->debug('Calculated median score', ['cid' => $cid, 'divider' => $divider, 'median' => $score]);
443 * Computes the displayed items.
445 * Community pages have a restriction on how many successive posts by the same author can show on any given page,
446 * so we may have to retrieve more content beyond the first query
451 protected function getCommunityItems()
453 $items = $this->selectItems();
455 $maxpostperauthor = (int) $this->config->get('system', 'max_author_posts_community_page');
456 if ($maxpostperauthor != 0 && $this->selectedTab == 'local') {
458 $previousauthor = '';
460 $selected_items = [];
462 while (count($selected_items) < $this->itemsPerPage && ++$count < 50 && count($items) > 0) {
463 foreach ($items as $item) {
464 if ($previousauthor == $item["author-link"]) {
469 $previousauthor = $item["author-link"];
471 if (($numposts < $maxpostperauthor) && (count($selected_items) < $this->itemsPerPage)) {
472 $selected_items[] = $item;
476 // If we're looking at a "previous page", the lookup continues forward in time because the list is
477 // sorted in chronologically decreasing order
478 if (isset($this->minId)) {
479 $this->minId = $items[0]['received'];
481 // In any other case, the lookup continues backwards in time
482 $this->maxId = $items[count($items) - 1]['received'];
485 $items = $this->selectItems();
488 $selected_items = $items;
491 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => array_column($selected_items, 'uri-id')];
492 $this->setItemsSeenByCondition($condition);
494 return $selected_items;
498 * Database query for the community page
502 * @TODO Move to repository/factory
504 private function selectItems()
506 if ($this->selectedTab == 'local') {
507 $condition = ["`wall` AND `origin` AND `private` = ?", Item::PUBLIC];
508 } elseif ($this->selectedTab == 'global') {
509 $condition = ["`uid` = ? AND `private` = ?", 0, Item::PUBLIC];
514 if (!is_null($this->accountType)) {
515 $condition = DBA::mergeConditions($condition, ['owner-contact-type' => $this->accountType]);
518 $params = ['order' => ['received' => true], 'limit' => $this->itemsPerPage];
520 if (!empty($this->itemUriId)) {
521 $condition = DBA::mergeConditions($condition, ['uri-id' => $this->itemUriId]);
523 if ($this->session->getLocalUserId() && $this->noSharer) {
524 $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()]);
527 if (isset($this->maxId)) {
528 $condition = DBA::mergeConditions($condition, ["`received` < ?", $this->maxId]);
531 if (isset($this->minId)) {
532 $condition = DBA::mergeConditions($condition, ["`received` > ?", $this->minId]);
534 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
535 if (!isset($this->maxId)) {
536 $params['order']['received'] = false;
541 $r = Post::selectThreadForUser($this->session->getLocalUserId() ?: 0, ['uri-id', 'received', 'author-link'], $condition, $params);
543 $items = Post::toArray($r);
548 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
549 if (empty($this->itemUriId) && isset($this->minId) && !isset($this->maxId)) {
550 $items = array_reverse($items);
559 * @param array $condition The array with the SQL condition
560 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
562 protected function setItemsSeenByCondition(array $condition)
564 if (empty($condition)) {
568 $unseen = Post::exists($condition);
571 /// @todo handle huge "unseen" updates in the background to avoid timeout errors
572 Item::update(['unseen' => false], $condition);