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\Model\Item;
40 use Friendica\Model\Post;
41 use Friendica\Module\Response;
42 use Friendica\Util\DateTimeFormat;
43 use Friendica\Util\Profiler;
44 use Psr\Log\LoggerInterface;
46 class Timeline extends BaseModule
49 protected static $selectedTab;
51 protected static $min_id;
53 protected static $max_id;
55 protected static $accountTypeString;
57 protected static $accountType;
59 protected static $item_id;
61 protected static $itemsPerPage;
63 protected static $no_sharer;
65 /** @var App\Mode $mode */
67 /** @var UserSession */
71 /** @var IManagePersonalConfigValues */
73 /** @var IManageConfigValues The config */
78 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 = [])
80 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
83 $this->session = $session;
84 $this->database = $database;
85 $this->pConfig = $pConfig;
86 $this->config = $config;
87 $this->cache = $cache;
91 * Computes module parameters from the request and local configuration
93 * @throws HTTPException\BadRequestException
94 * @throws HTTPException\ForbiddenException
96 protected function parseRequest(array $request)
98 self::$selectedTab = $this->parameters['content'] ?? '';
100 self::$accountTypeString = $request['accounttype'] ?? $this->parameters['accounttype'] ?? '';
101 self::$accountType = User::getAccountTypeByString(self::$accountTypeString);
103 if ($this->mode->isMobile()) {
104 self::$itemsPerPage = $this->pConfig->get(
105 $this->session->getLocalUserId(),
107 'itemspage_mobile_network',
108 $this->config->get('system', 'itemspage_network_mobile')
111 self::$itemsPerPage = $this->pConfig->get(
112 $this->session->getLocalUserId(),
115 $this->config->get('system', 'itemspage_network')
119 self::$min_id = $request['min_id'] ?? null;
120 self::$max_id = $request['max_id'] ?? null;
122 self::$no_sharer = !empty($request['no_sharer']);
125 protected function getNoSharerWidget(string $base): string
127 $path = self::$selectedTab;
128 if (!empty(self::$accountTypeString)) {
129 $path .= '/' . self::$accountTypeString;
131 $query_parameters = [];
133 if (!empty(self::$min_id)) {
134 $query_parameters['min_id'] = self::$min_id;
136 if (!empty(self::$max_id)) {
137 $query_parameters['max_id'] = self::$max_id;
140 $path_all = $path . (!empty($query_parameters) ? '?' . http_build_query($query_parameters) : '');
141 $path_no_sharer = $path . '?' . http_build_query(array_merge($query_parameters, ['no_sharer' => true]));
142 return Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/community_sharer.tpl'), [
143 '$title' => $this->l10n->t('Own Contacts'),
144 '$path_all' => $path_all,
145 '$path_no_sharer' => $path_no_sharer,
146 '$no_sharer' => self::$no_sharer,
147 '$all' => $this->l10n->t('Include'),
148 '$no_sharer_label' => $this->l10n->t('Hide'),
153 protected function getTabArray(Timelines $timelines, string $prefix): array
157 foreach ($timelines as $tab) {
159 'label' => $tab->label,
160 'url' => $tab->path ?? $prefix . '/' . $tab->code,
161 'sel' => self::$selectedTab == $tab->code ? 'active' : '',
162 'title' => $tab->description,
163 'id' => $prefix . '-' . $tab->code . '-tab',
164 'accesskey' => $tab->accessKey,
171 * Database query for the channel page
176 protected function getChannelItems()
178 $uid = $this->session->getLocalUserId();
180 if (self::$selectedTab == TimelineEntity::WHATSHOT) {
181 if (!is_null(self::$accountType)) {
182 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` = ?", $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), self::$accountType];
184 $condition = ["(`comments` >= ? OR `activities` >= ?) AND `contact-type` != ?", $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), Contact::TYPE_COMMUNITY];
186 } elseif (self::$selectedTab == TimelineEntity::FORYOU) {
187 $cid = Contact::getPublicIdByUserId($uid);
190 "(`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `relation-thread-score` > ?) OR
191 ((`comments` >= ? OR `activities` >= ?) AND `owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ?)) OR
192 (`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` IN (?, ?) AND `notify_new_posts`)))",
193 $cid, $this->getMedianRelationThreadScore($cid, 4), $this->getMedianComments($uid, 4), $this->getMedianActivities($uid, 4), $cid,
194 $uid, Contact::FRIEND, Contact::SHARING
196 } elseif (self::$selectedTab == TimelineEntity::FOLLOWERS) {
197 $condition = ["`owner-id` IN (SELECT `pid` FROM `account-user-view` WHERE `uid` = ? AND `rel` = ?)", $uid, Contact::FOLLOWER];
198 } elseif (self::$selectedTab == TimelineEntity::SHARERSOFSHARERS) {
199 $cid = Contact::getPublicIdByUserId($uid);
201 // @todo Suggest posts from contacts that are followed most by our followers
203 "`owner-id` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `last-interaction` > ?
204 AND `relation-cid` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ? AND `relation-thread-score` >= ?)
205 AND NOT `cid` IN (SELECT `cid` FROM `contact-relation` WHERE `follows` AND `relation-cid` = ?))",
206 DateTimeFormat::utc('now - ' . $this->config->get('channel', 'sharer_interaction_days') . ' day'), $cid, $this->getMedianRelationThreadScore($cid, 4), $cid
208 } elseif (self::$selectedTab == TimelineEntity::IMAGE) {
209 $condition = ["`media-type` & ?", 1];
210 } elseif (self::$selectedTab == TimelineEntity::VIDEO) {
211 $condition = ["`media-type` & ?", 2];
212 } elseif (self::$selectedTab == TimelineEntity::AUDIO) {
213 $condition = ["`media-type` & ?", 4];
214 } elseif (self::$selectedTab == TimelineEntity::LANGUAGE) {
215 $condition = ["JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?", $this->l10n->convertCodeForLanguageDetection(User::getLanguageCode($uid))];
218 if (self::$selectedTab != TimelineEntity::LANGUAGE) {
219 $condition = $this->addLanguageCondition($uid, $condition);
222 $condition[0] .= " AND NOT EXISTS(SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` = `post-engagement`.`owner-id` AND (`ignored` OR `blocked` OR `collapsed`))";
225 if ((self::$selectedTab != TimelineEntity::WHATSHOT) && !is_null(self::$accountType)) {
226 $condition[0] .= " AND `contact-type` = ?";
227 $condition[] = self::$accountType;
230 $params = ['order' => ['created' => true], 'limit' => self::$itemsPerPage];
232 if (!empty(self::$item_id)) {
233 $condition[0] .= " AND `uri-id` = ?";
234 $condition[] = self::$item_id;
236 if (self::$no_sharer) {
237 $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`)";
241 if (isset(self::$max_id)) {
242 $condition[0] .= " AND `created` < ?";
243 $condition[] = self::$max_id;
246 if (isset(self::$min_id)) {
247 $condition[0] .= " AND `created` > ?";
248 $condition[] = self::$min_id;
250 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
251 if (!isset(self::$max_id)) {
252 $params['order']['created'] = false;
257 $items = $this->database->selectToArray('post-engagement', ['uri-id', 'created'], $condition, $params);
262 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
263 if (empty(self::$item_id) && isset(self::$min_id) && !isset(self::$max_id)) {
264 $items = array_reverse($items);
267 Item::update(['unseen' => false], ['unseen' => true, 'uid' => $uid, 'uri-id' => array_column($items, 'uri-id')]);
272 private function addLanguageCondition(int $uid, array $condition): array
275 $languages = $this->pConfig->get($uid, 'channel', 'languages', [User::getLanguageCode($uid)]);
276 $languages = $this->l10n->convertForLanguageDetection($languages);
277 foreach ($languages as $language) {
278 $conditions[] = "JSON_EXTRACT(JSON_KEYS(language), '$[0]') = ?";
279 $condition[] = $language;
281 if (!empty($conditions)) {
282 $condition[0] .= " AND (`language` IS NULL OR " . implode(' OR ', $conditions) . ")";
287 private function getMedianComments(int $uid, int $divider): int
289 $languages = $this->pConfig->get($uid, 'channel', 'languages', [User::getLanguageCode($uid)]);
290 $cache_key = 'Channel:getMedianComments:' . $divider . ':' . implode(':', $languages);
291 $comments = $this->cache->get($cache_key);
292 if (!empty($comments)) {
296 $condition = ["`contact-type` != ? AND `comments` > ?", Contact::TYPE_COMMUNITY, 0];
297 $condition = $this->addLanguageCondition($uid, $condition);
299 $limit = $this->database->count('post-engagement', $condition) / $divider;
300 $post = $this->database->selectToArray('post-engagement', ['comments'], $condition, ['order' => ['comments' => true], 'limit' => [$limit, 1]]);
301 $comments = $post[0]['comments'] ?? 0;
302 if (empty($comments)) {
306 $this->cache->set($cache_key, $comments, Duration::HALF_HOUR);
307 $this->logger->debug('Calculated median comments', ['divider' => $divider, 'languages' => $languages, 'median' => $comments]);
311 private function getMedianActivities(int $uid, int $divider): int
313 $languages = $this->pConfig->get($uid, 'channel', 'languages', [User::getLanguageCode($uid)]);
314 $cache_key = 'Channel:getMedianActivities:' . $divider . ':' . implode(':', $languages);
315 $activities = $this->cache->get($cache_key);
316 if (!empty($activities)) {
320 $condition = ["`contact-type` != ? AND `activities` > ?", Contact::TYPE_COMMUNITY, 0];
321 $condition = $this->addLanguageCondition($uid, $condition);
323 $limit = $this->database->count('post-engagement', $condition) / $divider;
324 $post = $this->database->selectToArray('post-engagement', ['activities'], $condition, ['order' => ['activities' => true], 'limit' => [$limit, 1]]);
325 $activities = $post[0]['activities'] ?? 0;
326 if (empty($activities)) {
330 $this->cache->set($cache_key, $activities, Duration::HALF_HOUR);
331 $this->logger->debug('Calculated median activities', ['divider' => $divider, 'languages' => $languages, 'median' => $activities]);
335 private function getMedianRelationThreadScore(int $cid, int $divider): int
337 $cache_key = 'Channel:getThreadScore:' . $cid . ':' . $divider;
338 $score = $this->cache->get($cache_key);
339 if (!empty($score)) {
343 $condition = ["`relation-cid` = ? AND `relation-thread-score` > ?", $cid, 0];
345 $limit = $this->database->count('contact-relation', $condition) / $divider;
346 $relation = $this->database->selectToArray('contact-relation', ['relation-thread-score'], $condition, ['order' => ['relation-thread-score' => true], 'limit' => [$limit, 1]]);
347 $score = $relation[0]['relation-thread-score'] ?? 0;
352 $this->cache->set($cache_key, $score, Duration::HALF_HOUR);
353 $this->logger->debug('Calculated median score', ['cid' => $cid, 'divider' => $divider, 'median' => $score]);
358 * Computes the displayed items.
360 * Community pages have a restriction on how many successive posts by the same author can show on any given page,
361 * so we may have to retrieve more content beyond the first query
366 protected function getCommunityItems()
368 $items = $this->selectItems();
370 $maxpostperauthor = (int) $this->config->get('system', 'max_author_posts_community_page');
371 if ($maxpostperauthor != 0 && self::$selectedTab == 'local') {
373 $previousauthor = '';
375 $selected_items = [];
377 while (count($selected_items) < self::$itemsPerPage && ++$count < 50 && count($items) > 0) {
378 foreach ($items as $item) {
379 if ($previousauthor == $item["author-link"]) {
384 $previousauthor = $item["author-link"];
386 if (($numposts < $maxpostperauthor) && (count($selected_items) < self::$itemsPerPage)) {
387 $selected_items[] = $item;
391 // If we're looking at a "previous page", the lookup continues forward in time because the list is
392 // sorted in chronologically decreasing order
393 if (isset(self::$min_id)) {
394 self::$min_id = $items[0]['commented'];
396 // In any other case, the lookup continues backwards in time
397 self::$max_id = $items[count($items) - 1]['commented'];
400 $items = $this->selectItems();
403 $selected_items = $items;
406 return $selected_items;
410 * Database query for the community page
414 * @TODO Move to repository/factory
416 private function selectItems()
418 if (self::$selectedTab == 'local') {
419 if (!is_null(self::$accountType)) {
420 $condition = ["`wall` AND `origin` AND `private` = ? AND `owner-contact-type` = ?", Item::PUBLIC, self::$accountType];
422 $condition = ["`wall` AND `origin` AND `private` = ?", Item::PUBLIC];
424 } elseif (self::$selectedTab == 'global') {
425 if (!is_null(self::$accountType)) {
426 $condition = ["`uid` = ? AND `private` = ? AND `owner-contact-type` = ?", 0, Item::PUBLIC, self::$accountType];
428 $condition = ["`uid` = ? AND `private` = ?", 0, Item::PUBLIC];
434 $params = ['order' => ['commented' => true], 'limit' => self::$itemsPerPage];
436 if (!empty(self::$item_id)) {
437 $condition[0] .= " AND `id` = ?";
438 $condition[] = self::$item_id;
440 if ($this->session->getLocalUserId() && self::$no_sharer) {
441 $condition[0] .= " AND 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`)";
442 $condition[] = $this->session->getLocalUserId();
445 if (isset(self::$max_id)) {
446 $condition[0] .= " AND `commented` < ?";
447 $condition[] = self::$max_id;
450 if (isset(self::$min_id)) {
451 $condition[0] .= " AND `commented` > ?";
452 $condition[] = self::$min_id;
454 // Previous page case: we want the items closest to min_id but for that we need to reverse the query order
455 if (!isset(self::$max_id)) {
456 $params['order']['commented'] = false;
461 $r = Post::selectThreadForUser($this->session->getLocalUserId() ?: 0, ['uri-id', 'commented', 'author-link'], $condition, $params);
463 $items = Post::toArray($r);
468 // Previous page case: once we get the relevant items closest to min_id, we need to restore the expected display order
469 if (empty(self::$item_id) && isset(self::$min_id) && !isset(self::$max_id)) {
470 $items = array_reverse($items);