3 * @copyright Copyright (C) 2010-2024, 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\Content\BoundariesPager;
27 use Friendica\Content\Conversation;
28 use Friendica\Content\Conversation\Entity\Network as NetworkEntity;
29 use Friendica\Content\Conversation\Factory\Timeline as TimelineFactory;
30 use Friendica\Content\Conversation\Repository\UserDefinedChannel;
31 use Friendica\Content\Conversation\Factory\Channel as ChannelFactory;
32 use Friendica\Content\Conversation\Factory\UserDefinedChannel as UserDefinedChannelFactory;
33 use Friendica\Content\Conversation\Factory\Community as CommunityFactory;
34 use Friendica\Content\Conversation\Factory\Network as NetworkFactory;
35 use Friendica\Content\Feature;
36 use Friendica\Content\GroupManager;
37 use Friendica\Content\Nav;
38 use Friendica\Content\Widget;
39 use Friendica\Content\Text\HTML;
40 use Friendica\Content\Widget\TrendingTags;
41 use Friendica\Core\ACL;
42 use Friendica\Core\Cache\Capability\ICanCache;
43 use Friendica\Core\Config\Capability\IManageConfigValues;
44 use Friendica\Core\Hook;
45 use Friendica\Core\L10n;
46 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
47 use Friendica\Core\Renderer;
48 use Friendica\Core\Session\Capability\IHandleUserSessions;
49 use Friendica\Database\DBA;
50 use Friendica\Database\Database;
51 use Friendica\Model\Contact;
52 use Friendica\Model\Circle;
53 use Friendica\Model\Profile;
54 use Friendica\Module\Response;
55 use Friendica\Module\Security\Login;
56 use Friendica\Network\HTTPException;
57 use Friendica\Navigation\SystemMessages;
58 use Friendica\Util\DateTimeFormat;
59 use Friendica\Util\Profiler;
60 use Psr\Log\LoggerInterface;
62 class Network extends Timeline
83 /** @var IManageConfigValues The config */
85 /** @var SystemMessages */
86 protected $systemMessages;
89 /** @var Conversation */
90 protected $conversation;
91 /** @var IManagePersonalConfigValues */
95 /** @var TimelineFactory */
97 /** @var ChannelFactory */
99 /** @var UserDefinedChannelFactory */
100 protected $userDefinedChannel;
101 /** @var CommunityFactory */
102 protected $community;
103 /** @var NetworkFactory */
104 protected $networkFactory;
106 public function __construct(UserDefinedChannelFactory $userDefinedChannel, NetworkFactory $network, CommunityFactory $community, ChannelFactory $channelFactory, UserDefinedChannel $channel, App $app, TimelineFactory $timeline, SystemMessages $systemMessages, Mode $mode, Conversation $conversation, App\Page $page, 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 = [])
108 parent::__construct($channel, $mode, $session, $database, $pConfig, $config, $cache, $l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
111 $this->timeline = $timeline;
112 $this->systemMessages = $systemMessages;
113 $this->conversation = $conversation;
115 $this->channel = $channelFactory;
116 $this->community = $community;
117 $this->networkFactory = $network;
118 $this->userDefinedChannel = $userDefinedChannel;
121 protected function content(array $request = []): string
123 if (!$this->session->getLocalUserId()) {
124 return Login::form();
127 $this->parseRequest($request);
131 $arr = ['query' => $this->args->getQueryString()];
132 Hook::callAll('network_content_init', $arr);
136 $this->page['aside'] .= Circle::sidebarWidget($module, $module . '/circle', 'standard', $this->circleId);
137 $this->page['aside'] .= GroupManager::widget($this->session->getLocalUserId());
138 $this->page['aside'] .= Widget::postedByYear($module . '/archive', $this->session->getLocalUserId(), false);
139 $this->page['aside'] .= Widget::networks($module, $this->network);
140 $this->page['aside'] .= Widget::accountTypes($module, $this->accountTypeString);
141 $this->page['aside'] .= Widget::channels($module, $this->selectedTab, $this->session->getLocalUserId());
142 $this->page['aside'] .= Widget\SavedSearches::getHTML($this->args->getQueryString());
143 $this->page['aside'] .= Widget::fileAs('filed', '');
145 if (Feature::isEnabled($this->session->getLocalUserId(), 'trending_tags')) {
146 $this->page['aside'] .= TrendingTags::getHTML($this->selectedTab);
149 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll') && ($_GET['mode'] ?? '') != 'minimal') {
150 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
151 $o .= Renderer::replaceMacros($tpl, ['$reload_uri' => $this->args->getQueryString()]);
155 $o .= $this->getTabsHTML();
157 Nav::setSelected($this->args->get(0));
161 $default_permissions = [];
162 if ($this->circleId) {
163 $default_permissions['allow_gid'] = [$this->circleId];
167 if ($this->network) {
169 'uid' => $this->session->getLocalUserId(),
170 'network' => $this->network,
175 'rel' => [Contact::SHARING, Contact::FRIEND],
177 $contactStmt = $this->database->select('contact', ['id'], $condition);
178 while ($contact = $this->database->fetch($contactStmt)) {
179 $allowedCids[] = (int) $contact['id'];
181 $this->database->close($contactStmt);
184 if (count($allowedCids)) {
185 $default_permissions['allow_cid'] = $allowedCids;
189 'lockstate' => $this->circleId || $this->network || ACL::getLockstateForUserId($this->session->getLocalUserId()) ? 'lock' : 'unlock',
190 'acl' => ACL::getFullSelectorHTML($this->page, $this->session->getLocalUserId(), true, $default_permissions),
191 'bang' => (($this->circleId || $this->network) ? '!' : ''),
192 'content' => $content,
195 $o .= $this->conversation->statusEditor($x);
197 if ($this->circleId) {
198 $circle = $this->database->selectFirst('group', ['name'], ['id' => $this->circleId, 'uid' => $this->session->getLocalUserId()]);
199 if (!$this->database->isResult($circle)) {
200 $this->systemMessages->addNotice($this->l10n->t('No such circle'));
203 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
204 '$title' => $this->l10n->t('Circle: %s', $circle['name'])
206 } elseif (Profile::shouldDisplayEventList($this->session->getLocalUserId(), $this->mode)) {
207 $o .= Profile::getBirthdays($this->session->getLocalUserId());
208 $o .= Profile::getEventsReminderHTML($this->session->getLocalUserId(), $this->session->getPublicContactId());
213 if ($this->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId())) {
214 $items = $this->getChannelItems();
215 } elseif ($this->community->isTimeline($this->selectedTab)) {
216 $items = $this->getCommunityItems();
218 $items = $this->getItems();
221 $o .= $this->conversation->render($items, Conversation::MODE_NETWORK, false, false, $this->getOrder(), $this->session->getLocalUserId());
222 } catch (\Exception $e) {
223 $o .= $this->l10n->t('Error %d (%s) while fetching the timeline.', $e->getCode(), $e->getMessage());
226 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
227 $o .= HTML::scrollLoader();
229 $pager = new BoundariesPager(
231 $this->args->getQueryString(),
232 $items[0][$this->order] ?? null,
233 $items[count($items) - 1][$this->order] ?? null,
237 $o .= $pager->renderMinimal(count($items));
243 protected function getOrder(): string
245 if ($this->order === 'received') {
247 } elseif ($this->order === 'created') {
250 return '`commented`';
255 * Get the network tabs menu
257 * @return string Html of the network tabs
258 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
260 private function getTabsHTML()
262 $tabs = $this->getTabArray($this->networkFactory->getTimelines($this->args->getCommand()), 'network');
264 $network_timelines = $this->pConfig->get($this->session->getLocalUserId(), 'system', 'network_timelines', []);
265 if (!empty($network_timelines)) {
266 $tabs = array_merge($tabs, $this->getTabArray($this->channel->getTimelines($this->session->getLocalUserId()), 'network', 'channel'));
267 $tabs = array_merge($tabs, $this->getTabArray($this->channelRepository->selectByUid($this->session->getLocalUserId()), 'network', 'channel'));
268 $tabs = array_merge($tabs, $this->getTabArray($this->community->getTimelines(true), 'network', 'channel'));
271 $arr = ['tabs' => $tabs];
272 Hook::callAll('network_tabs', $arr);
274 if (!empty($network_timelines)) {
277 foreach ($arr['tabs'] as $tab) {
278 if (in_array($tab['code'], $network_timelines)) {
283 $tabs = $arr['tabs'];
286 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
288 return Renderer::replaceMacros($tpl, ['$tabs' => $tabs]);
291 protected function parseRequest(array $request)
293 parent::parseRequest($request);
295 $this->circleId = (int)($this->parameters['circle_id'] ?? 0);
297 if (!$this->selectedTab) {
298 $this->selectedTab = self::getTimelineOrderBySession($this->session, $this->pConfig);
299 } elseif (!$this->networkFactory->isTimeline($this->selectedTab) && !$this->channel->isTimeline($this->selectedTab) && !$this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId()) && !$this->community->isTimeline($this->selectedTab)) {
300 throw new HTTPException\BadRequestException($this->l10n->t('Network feed not available.'));
303 if (($this->network || $this->circleId) && ($this->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId()) || $this->community->isTimeline($this->selectedTab))) {
304 $this->selectedTab = NetworkEntity::RECEIVED;
307 if (!empty($request['star'])) {
308 $this->selectedTab = NetworkEntity::STAR;
311 $this->star = $this->selectedTab == NetworkEntity::STAR;
314 if (!empty($request['mention'])) {
315 $this->selectedTab = NetworkEntity::MENTION;
316 $this->mention = true;
318 $this->mention = $this->selectedTab == NetworkEntity::MENTION;
321 if (!empty($request['order'])) {
322 $this->selectedTab = $request['order'];
323 $this->order = $request['order'];
325 $this->mention = false;
326 } elseif (in_array($this->selectedTab, [NetworkEntity::RECEIVED, NetworkEntity::STAR]) || $this->community->isTimeline($this->selectedTab)) {
327 $this->order = 'received';
328 } elseif (($this->selectedTab == NetworkEntity::CREATED) || $this->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId())) {
329 $this->order = 'created';
331 $this->order = 'commented';
334 $this->selectedTab = $this->selectedTab ?? $this->order;
336 // Upon updates in the background and order by last comment we order by received date,
337 // since otherwise the feed will optically jump, when some already visible thread has been updated.
338 if ($this->update && ($this->selectedTab == NetworkEntity::COMMENTED)) {
339 $this->order = 'received';
340 $request['last_received'] = $request['last_commented'] ?? null;
341 $request['first_received'] = $request['first_commented'] ?? null;
344 // Prohibit combined usage of "star" and "mention"
345 if ($this->selectedTab == NetworkEntity::STAR) {
346 $this->mention = false;
347 } elseif ($this->selectedTab == NetworkEntity::MENTION) {
351 $this->session->set('network-tab', $this->selectedTab);
352 $this->pConfig->set($this->session->getLocalUserId(), 'network.view', 'selected_tab', $this->selectedTab);
354 $this->network = $request['nets'] ?? '';
356 $this->dateFrom = $this->parameters['from'] ?? '';
357 $this->dateTo = $this->parameters['to'] ?? '';
359 switch ($this->order) {
361 $this->maxId = $request['last_received'] ?? $this->maxId;
362 $this->minId = $request['first_received'] ?? $this->minId;
365 $this->maxId = $request['last_created'] ?? $this->maxId;
366 $this->minId = $request['first_created'] ?? $this->minId;
369 $this->maxId = $request['last_uriid'] ?? $this->maxId;
370 $this->minId = $request['first_uriid'] ?? $this->minId;
373 $this->order = 'commented';
374 $this->maxId = $request['last_commented'] ?? $this->maxId;
375 $this->minId = $request['first_commented'] ?? $this->minId;
379 protected function getItems()
381 $conditionFields = ['uid' => $this->session->getLocalUserId()];
382 $conditionStrings = [];
384 if (!is_null($this->accountType)) {
385 $conditionFields['contact-type'] = $this->accountType;
389 $conditionFields['starred'] = true;
391 if ($this->mention) {
392 $conditionFields['mention'] = true;
394 if ($this->network) {
395 $conditionFields['network'] = $this->network;
398 if ($this->dateFrom) {
399 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` <= ? ", DateTimeFormat::convert($this->dateFrom, 'UTC', $this->app->getTimeZone())]);
402 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` >= ? ", DateTimeFormat::convert($this->dateTo, 'UTC', $this->app->getTimeZone())]);
405 if ($this->circleId) {
406 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`contact-id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)", $this->circleId]);
409 // Currently only the order modes "received" and "commented" are in use
410 if (!empty($this->itemUriId)) {
411 $conditionStrings = DBA::mergeConditions($conditionStrings, ['uri-id' => $this->itemUriId]);
413 if (isset($this->maxId)) {
414 switch ($this->order) {
416 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` < ?", $this->maxId]);
419 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` < ?", $this->maxId]);
422 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` < ?", $this->maxId]);
425 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` < ?", $this->maxId]);
430 if (isset($this->minId)) {
431 switch ($this->order) {
433 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` > ?", $this->minId]);
436 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` > ?", $this->minId]);
439 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` > ?", $this->minId]);
442 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` > ?", $this->minId]);
448 $params = ['limit' => $this->itemsPerPage];
450 if (isset($this->minId) && !isset($this->maxId)) {
451 // min_id quirk: querying in reverse order with min_id gets the most recent rows, regardless of how close
452 // they are to min_id. We change the query ordering to get the expected data, and we need to reverse the
453 // order of the results.
454 $params['order'] = [$this->order => false];
456 $params['order'] = [$this->order => true];
459 $items = $this->database->selectToArray('network-thread-view', [], DBA::mergeConditions($conditionFields, $conditionStrings), $params);
461 // min_id quirk, continued
462 if (isset($this->minId) && !isset($this->maxId)) {
463 $items = array_reverse($items);
466 if ($this->database->isResult($items)) {
467 $parents = array_column($items, 'uri-id');
472 // We aren't going to try and figure out at the item, circle, and page
473 // level which items you've seen and which you haven't. If you're looking
474 // at the top level network page just mark everything seen.
475 if (!$this->circleId && !$this->star && !$this->mention) {
476 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId()];
477 $this->setItemsSeenByCondition($condition);
478 } elseif (!empty($parents)) {
479 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => $parents];
480 $this->setItemsSeenByCondition($condition);
487 * Returns the selected network tab of the currently logged-in user
489 * @param IHandleUserSessions $session
490 * @param IManagePersonalConfigValues $pconfig
493 public static function getTimelineOrderBySession(IHandleUserSessions $session, IManagePersonalConfigValues $pconfig): string
495 return $session->get('network-tab')
496 ?? $pconfig->get($session->getLocalUserId(), 'network.view', 'selected_tab')