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\Channel as ChannelEntity;
29 use Friendica\Content\Conversation\Repository\UserDefinedChannel;
30 use Friendica\Core\Cache\Capability\ICanCache;
31 use Friendica\Core\Cache\Enum\Duration;
32 use Friendica\Core\Config\Capability\IManageConfigValues;
33 use Friendica\Core\L10n;
34 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
35 use Friendica\Core\Renderer;
36 use Friendica\Core\Session\Capability\IHandleUserSessions;
37 use Friendica\Model\Contact;
38 use Friendica\Model\User;
39 use Friendica\Database\Database;
40 use Friendica\Database\DBA;
41 use Friendica\Model\Item;
42 use Friendica\Model\Post;
43 use Friendica\Model\Post\Engagement;
44 use Friendica\Module\Response;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Profiler;
47 use Psr\Log\LoggerInterface;
49 class Timeline extends BaseModule
52 protected $selectedTab;
58 protected $accountTypeString;
60 protected $accountType;
64 protected $itemsPerPage;
74 /** @var App\Mode $mode */
76 /** @var IHandleUserSessions */
80 /** @var IManagePersonalConfigValues */
82 /** @var IManageConfigValues The config */
86 /** @var UserDefinedChannel */
87 protected $channelRepository;
89 public function __construct(UserDefinedChannel $channel, 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 = [])
91 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
93 $this->channelRepository = $channel;
95 $this->session = $session;
96 $this->database = $database;
97 $this->pConfig = $pConfig;
98 $this->config = $config;
99 $this->cache = $cache;
103 * Computes module parameters from the request and local configuration
105 * @throws HTTPException\BadRequestException
106 * @throws HTTPException\ForbiddenException
108 protected function parseRequest(array $request)
110 $this->logger->debug('Got request', $request);
111 $this->selectedTab = $this->parameters['content'] ?? $request['channel'] ?? '';
113 $this->accountTypeString = $request['accounttype'] ?? $this->parameters['accounttype'] ?? '';
114 $this->accountType = User::getAccountTypeByString($this->accountTypeString);
116 if ($this->mode->isMobile()) {
117 $this->itemsPerPage = $this->pConfig->get(
118 $this->session->getLocalUserId(),
120 'itemspage_mobile_network',
121 $this->config->get('system', 'itemspage_network_mobile')
124 $this->itemsPerPage = $this->pConfig->get(
125 $this->session->getLocalUserId(),
128 $this->config->get('system', 'itemspage_network')
132 if (!empty($request['item'])) {
133 $item = Post::selectFirst(['parent', 'parent-uri-id'], ['id' => $request['item']]);
134 $this->itemUriId = $item['parent-uri-id'] ?? 0;
136 $this->itemUriId = 0;
139 $this->minId = $request['min_id'] ?? null;
140 $this->maxId = $request['max_id'] ?? null;
142 $this->noSharer = !empty($request['no_sharer']);
143 $this->force = !empty($request['force']) && !empty($request['item']);
144 $this->update = !empty($request['force']) && !empty($request['first_received']) && !empty($request['first_created']) && !empty($request['first_uriid']) && !empty($request['first_commented']);
145 $this->raw = !empty($request['mode']) && ($request['mode'] == 'raw');
148 protected function getNoSharerWidget(string $base): string
150 $path = $this->selectedTab;
151 if (!empty($this->accountTypeString)) {
152 $path .= '/' . $this->accountTypeString;
154 $query_parameters = [];
156 if (!empty($this->minId)) {
157 $query_parameters['min_id'] = $this->minId;
159 if (!empty($this->maxId)) {
160 $query_parameters['max_id'] = $this->maxId;
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 return Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/community_sharer.tpl'), [
166 '$title' => $this->l10n->t('Own Contacts'),
167 '$path_all' => $path_all,
168 '$path_no_sharer' => $path_no_sharer,
169 '$no_sharer' => $this->noSharer,
170 '$all' => $this->l10n->t('Include'),
171 '$no_sharer_label' => $this->l10n->t('Hide'),
176 protected function getTabArray(Timelines $timelines, string $prefix, string $parameter = ''): array
180 foreach ($timelines as $tab) {
181 if (is_null($tab->path) && !empty($parameter)) {
182 $path = $prefix . '?' . http_build_query([$parameter => $tab->code]);
184 $path = $tab->path ?? $prefix . '/' . $tab->code;
186 $tabs[$tab->code] = [
187 'code' => $tab->code,
188 'label' => $tab->label,
190 'sel' => $this->selectedTab == $tab->code ? 'active' : '',
191 'title' => $tab->description,
192 'id' => $prefix . '-' . $tab->code . '-tab',
193 'accesskey' => $tab->accessKey,
200 * Database query for the channel page
205 protected function getChannelItems()
207 $items = $this->getRawChannelItems();
209 $contacts = $this->database->selectToArray('user-contact', ['cid'], ['channel-frequency' => Contact\User::FREQUENCY_REDUCED, 'cid' => array_column($items, 'owner-id')]);
210 $reduced = array_column($contacts, 'cid');
212 $maxpostperauthor = $this->config->get('channel', 'max_posts_per_author');
214 if ($maxpostperauthor != 0) {
217 $selected_items = [];
219 while (count($selected_items) < $this->itemsPerPage && ++$count < 50 && count($items) > 0) {
220 $maxposts = round((count($items) / $this->itemsPerPage) * $maxpostperauthor);
221 $minId = $items[array_key_first($items)]['created'];
222 $maxId = $items[array_key_last($items)]['created'];
224 foreach ($items as $item) {
225 if (!in_array($item['owner-id'], $reduced)) {
228 $owner_posts[$item['owner-id']][$item['uri-id']] = (($item['comments'] * 100) + $item['activities']);
230 foreach ($owner_posts as $posts) {
231 if (count($posts) <= $maxposts) {
235 while (count($posts) > $maxposts) {
236 $uri_id = array_key_first($posts);
237 unset($posts[$uri_id]);
238 unset($items[$uri_id]);
241 $selected_items = array_merge($selected_items, $items);
243 // If we're looking at a "previous page", the lookup continues forward in time because the list is
244 // sorted in chronologically decreasing order
245 if (!empty($this->minId)) {
246 $this->minId = $minId;
248 // In any other case, the lookup continues backwards in time
249 $this->maxId = $maxId;
252 if (count($selected_items) < $this->itemsPerPage) {
253 $items = $this->getRawChannelItems();
257 $selected_items = $items;
260 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => array_column($selected_items, 'uri-id')];
261 $this->setItemsSeenByCondition($condition);
263 return $selected_items;
267 * Database query for the channel page
272 private function getRawChannelItems()
274 $uid = $this->session->getLocalUserId();
276 if ($this->selectedTab == ChannelEntity::WHATSHOT) {
277 if (!is_null($this->accountType)) {
278 $condition = ["(`comments` > ? OR `activities` > ?) AND `contact-type` = ?", $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), $this->accountType];
280 $condition = ["(`comments` > ? OR `activities` > ?) AND `contact-type` != ?", $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), Contact::TYPE_COMMUNITY];
282 } elseif ($this->selectedTab == ChannelEntity::FORYOU) {
283 $cid = Contact::getPublicIdByUserId($uid);
286 "(`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `relation-thread-score` > ?) OR
287 ((`comments` >= ? OR `activities` >= ?) AND `owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ?)) OR
288 (`owner-id` IN (SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND (`notify_new_posts` OR `channel-frequency` = ?))))",
289 $cid, $this->getMedianRelationThreadScore($cid, 4), $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), $cid,
290 $uid, Contact\User::FREQUENCY_ALWAYS
292 } elseif ($this->selectedTab == ChannelEntity::FOLLOWERS) {
293 $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` = ?)", $uid, Contact::FOLLOWER];
294 } elseif ($this->selectedTab == ChannelEntity::SHARERSOFSHARERS) {
295 $cid = Contact::getPublicIdByUserId($uid);
297 // @todo Suggest posts from contacts that are followed most by our followers
299 "`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `last-interaction` > ?
300 AND `relation-cid` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ? AND `relation-thread-score` >= ?)
301 AND NOT `cid` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ?))",
302 DateTimeFormat::utc('now - ' . $this->config->get('channel', 'sharer_interaction_days') . ' day'), $cid, $this->getMedianRelationThreadScore($cid, 4), $cid
304 } elseif ($this->selectedTab == ChannelEntity::IMAGE) {
305 $condition = ["`media-type` & ?", 1];
306 } elseif ($this->selectedTab == ChannelEntity::VIDEO) {
307 $condition = ["`media-type` & ?", 2];
308 } elseif ($this->selectedTab == ChannelEntity::AUDIO) {
309 $condition = ["`media-type` & ?", 4];
310 } elseif ($this->selectedTab == ChannelEntity::LANGUAGE) {
311 $condition = ["JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?", User::getLanguageCode($uid)];
312 } elseif (is_numeric($this->selectedTab)) {
313 $condition = $this->getUserChannelConditions($this->selectedTab, $this->session->getLocalUserId());
316 if ($this->selectedTab != ChannelEntity::LANGUAGE) {
317 $condition = $this->addLanguageCondition($uid, $condition);
320 $condition = DBA::mergeConditions($condition, ["(NOT `restricted` OR EXISTS(SELECT `id` FROM `post-user` WHERE `uid` = ? AND `uri-id` = `post-engagement`.`uri-id`))", $uid]);
322 $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]);
324 if (($this->selectedTab != ChannelEntity::WHATSHOT) && !is_null($this->accountType)) {
325 $condition = DBA::mergeConditions($condition, ['contact-type' => $this->accountType]);
328 $params = ['order' => ['created' => true], 'limit' => $this->itemsPerPage];
330 if (!empty($this->itemUriId)) {
331 $condition = DBA::mergeConditions($condition, ['uri-id' => $this->itemUriId]);
333 if ($this->noSharer) {
334 $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()]);
337 if (isset($this->maxId)) {
338 $condition = DBA::mergeConditions($condition, ["`created` < ?", $this->maxId]);
341 if (isset($this->minId)) {
342 $condition = DBA::mergeConditions($condition, ["`created` > ?", $this->minId]);
344 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
345 if (!isset($this->maxId)) {
346 $params['order']['created'] = false;
352 $result = $this->database->select('post-engagement', ['uri-id', 'created', 'owner-id', 'comments', 'activities'], $condition, $params);
353 if ($this->database->errorNo()) {
354 throw new \Exception($this->database->errorMessage(), $this->database->errorNo());
357 while ($item = $this->database->fetch($result)) {
358 $items[$item['uri-id']] = $item;
360 $this->database->close($result);
366 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
367 if (empty($this->itemUriId) && isset($this->minId) && !isset($this->maxId)) {
368 $items = array_reverse($items, true);
371 $condition = ['unseen' => true, 'uid' => $uid, 'parent-uri-id' => array_column($items, 'uri-id')];
372 $this->setItemsSeenByCondition($condition);
377 private function getUserChannelConditions(int $id, int $uid): array
379 $channel = $this->channelRepository->selectById($id, $uid);
380 if (empty($channel)) {
386 if (!empty($channel->circle)) {
387 if ($channel->circle == -1) {
388 $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` IN (?, ?))", $uid, Contact::SHARING, Contact::FRIEND];
389 } elseif ($channel->circle == -2) {
390 $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` = ?)", $uid, Contact::FOLLOWER];
391 } elseif ($channel->circle == -3) {
392 $condition = ["EXISTS(SELECT `uri-id` FROM `post-thread-user` WHERE `uid` = ? AND `post-thread-user`.`uri-id` = `post-engagement`.`uri-id`)", $uid];
393 } elseif ($channel->circle > 0) {
394 $condition = DBA::mergeConditions($condition, ["`owner-id` IN (SELECT `pid` FROM `group_member` INNER JOIN `account-user-view` ON `group_member`.`contact-id` = `account-user-view`.`id` WHERE `gid` = ? AND `account-user-view`.`uid` = ?)", $channel->circle, $uid]);
398 if (!empty($channel->fullTextSearch)) {
399 $search = $channel->fullTextSearch;
400 foreach (Engagement::KEYWORDS as $keyword) {
401 $search = preg_replace('~(' . $keyword . ':.[\w@\.-]+)~', '"$1"', $search);
403 $condition = DBA::mergeConditions($condition, ["MATCH (`searchtext`) AGAINST (? IN BOOLEAN MODE)", $search]);
406 if (!empty($channel->includeTags)) {
407 $search = explode(',', mb_strtolower($channel->includeTags));
408 $placeholders = substr(str_repeat("?, ", count($search)), 0, -2);
409 $condition = DBA::mergeConditions($condition, array_merge(["`uri-id` IN (SELECT `uri-id` FROM `post-tag` INNER JOIN `tag` ON `tag`.`id` = `post-tag`.`tid` WHERE `post-tag`.`type` = 1 AND `name` IN (" . $placeholders . "))"], $search));
412 if (!empty($channel->excludeTags)) {
413 $search = explode(',', mb_strtolower($channel->excludeTags));
414 $placeholders = substr(str_repeat("?, ", count($search)), 0, -2);
415 $condition = DBA::mergeConditions($condition, array_merge(["NOT `uri-id` IN (SELECT `uri-id` FROM `post-tag` INNER JOIN `tag` ON `tag`.`id` = `post-tag`.`tid` WHERE `post-tag`.`type` = 1 AND `name` IN (" . $placeholders . "))"], $search));
418 if (!empty($channel->mediaType)) {
419 $condition = DBA::mergeConditions($condition, ["`media-type` & ?", $channel->mediaType]);
422 // For "addLanguageCondition" to work, the condition must not be empty
423 return $condition ?: ["true"];
426 private function addLanguageCondition(int $uid, array $condition): array
429 $languages = User::getWantedLanguages($uid);
430 foreach ($languages as $language) {
431 $conditions[] = "JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?";
432 $condition[] = $language;
434 if (!empty($conditions)) {
435 $condition[0] .= " AND (`language` IS NULL OR " . implode(' OR ', $conditions) . ")";
440 private function getMedianComments(int $uid, int $divider): int
442 $languages = User::getWantedLanguages($uid);
443 $cache_key = 'Channel:getMedianComments:' . $divider . ':' . implode(':', $languages);
444 $comments = $this->cache->get($cache_key);
445 if (!empty($comments)) {
449 $condition = ["`contact-type` != ? AND `comments` > ? AND NOT `restricted`", Contact::TYPE_COMMUNITY, 0];
450 $condition = $this->addLanguageCondition($uid, $condition);
452 $limit = $this->database->count('post-engagement', $condition) / $divider;
453 $post = $this->database->selectToArray('post-engagement', ['comments'], $condition, ['order' => ['comments' => true], 'limit' => [$limit, 1]]);
454 $comments = $post[0]['comments'] ?? 0;
455 if (empty($comments)) {
459 $this->cache->set($cache_key, $comments, Duration::HALF_HOUR);
460 $this->logger->debug('Calculated median comments', ['divider' => $divider, 'languages' => $languages, 'median' => $comments]);
464 private function getMedianActivities(int $uid, int $divider): int
466 $languages = User::getWantedLanguages($uid);
467 $cache_key = 'Channel:getMedianActivities:' . $divider . ':' . implode(':', $languages);
468 $activities = $this->cache->get($cache_key);
469 if (!empty($activities)) {
473 $condition = ["`contact-type` != ? AND `activities` > ? AND NOT `restricted`", Contact::TYPE_COMMUNITY, 0];
474 $condition = $this->addLanguageCondition($uid, $condition);
476 $limit = $this->database->count('post-engagement', $condition) / $divider;
477 $post = $this->database->selectToArray('post-engagement', ['activities'], $condition, ['order' => ['activities' => true], 'limit' => [$limit, 1]]);
478 $activities = $post[0]['activities'] ?? 0;
479 if (empty($activities)) {
483 $this->cache->set($cache_key, $activities, Duration::HALF_HOUR);
484 $this->logger->debug('Calculated median activities', ['divider' => $divider, 'languages' => $languages, 'median' => $activities]);
488 private function getMedianRelationThreadScore(int $cid, int $divider): int
490 $cache_key = 'Channel:getThreadScore:' . $cid . ':' . $divider;
491 $score = $this->cache->get($cache_key);
492 if (!empty($score)) {
496 $condition = ["`relation-cid` = ? AND `relation-thread-score` > ?", $cid, 0];
498 $limit = $this->database->count('contact-relation', $condition) / $divider;
499 $relation = $this->database->selectToArray('contact-relation', ['relation-thread-score'], $condition, ['order' => ['relation-thread-score' => true], 'limit' => [$limit, 1]]);
500 $score = $relation[0]['relation-thread-score'] ?? 0;
505 $this->cache->set($cache_key, $score, Duration::HALF_HOUR);
506 $this->logger->debug('Calculated median score', ['cid' => $cid, 'divider' => $divider, 'median' => $score]);
511 * Computes the displayed items.
513 * Community pages have a restriction on how many successive posts by the same author can show on any given page,
514 * so we may have to retrieve more content beyond the first query
519 protected function getCommunityItems()
521 $items = $this->selectItems();
523 $maxpostperauthor = (int) $this->config->get('system', 'max_author_posts_community_page');
524 if ($maxpostperauthor != 0 && $this->selectedTab == 'local') {
526 $previousauthor = '';
528 $selected_items = [];
530 while (count($selected_items) < $this->itemsPerPage && ++$count < 50 && count($items) > 0) {
531 foreach ($items as $item) {
532 if ($previousauthor == $item["author-link"]) {
537 $previousauthor = $item["author-link"];
539 if (($numposts < $maxpostperauthor) && (count($selected_items) < $this->itemsPerPage)) {
540 $selected_items[] = $item;
544 // If we're looking at a "previous page", the lookup continues forward in time because the list is
545 // sorted in chronologically decreasing order
546 if (isset($this->minId)) {
547 $this->minId = $items[0]['received'];
549 // In any other case, the lookup continues backwards in time
550 $this->maxId = $items[count($items) - 1]['received'];
553 $items = $this->selectItems();
556 $selected_items = $items;
559 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => array_column($selected_items, 'uri-id')];
560 $this->setItemsSeenByCondition($condition);
562 return $selected_items;
566 * Database query for the community page
570 * @TODO Move to repository/factory
572 private function selectItems()
574 if ($this->selectedTab == 'local') {
575 $condition = ["`wall` AND `origin` AND `private` = ?", Item::PUBLIC];
576 } elseif ($this->selectedTab == 'global') {
577 $condition = ["`uid` = ? AND `private` = ?", 0, Item::PUBLIC];
582 if (!is_null($this->accountType)) {
583 $condition = DBA::mergeConditions($condition, ['owner-contact-type' => $this->accountType]);
586 $params = ['order' => ['received' => true], 'limit' => $this->itemsPerPage];
588 if (!empty($this->itemUriId)) {
589 $condition = DBA::mergeConditions($condition, ['uri-id' => $this->itemUriId]);
591 if ($this->session->getLocalUserId() && $this->noSharer) {
592 $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()]);
595 if (isset($this->maxId)) {
596 $condition = DBA::mergeConditions($condition, ["`received` < ?", $this->maxId]);
599 if (isset($this->minId)) {
600 $condition = DBA::mergeConditions($condition, ["`received` > ?", $this->minId]);
602 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
603 if (!isset($this->maxId)) {
604 $params['order']['received'] = false;
609 $r = Post::selectThreadForUser($this->session->getLocalUserId() ?: 0, ['uri-id', 'received', 'author-link'], $condition, $params);
611 $items = Post::toArray($r);
616 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
617 if (empty($this->itemUriId) && isset($this->minId) && !isset($this->maxId)) {
618 $items = array_reverse($items);
627 * @param array $condition The array with the SQL condition
628 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
630 protected function setItemsSeenByCondition(array $condition)
632 if (empty($condition)) {
636 $unseen = Post::exists($condition);
639 /// @todo handle huge "unseen" updates in the background to avoid timeout errors
640 Item::update(['unseen' => false], $condition);