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\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\Item;
54 use Friendica\Model\Profile;
55 use Friendica\Model\Verb;
56 use Friendica\Module\Contact as ModuleContact;
57 use Friendica\Module\Response;
58 use Friendica\Module\Security\Login;
59 use Friendica\Network\HTTPException;
60 use Friendica\Navigation\SystemMessages;
61 use Friendica\Util\DateTimeFormat;
62 use Friendica\Util\Profiler;
63 use Friendica\Protocol\Activity;
64 use Psr\Log\LoggerInterface;
66 class Network extends Timeline
71 protected $groupContactId;
89 /** @var IManageConfigValues The config */
91 /** @var SystemMessages */
92 protected $systemMessages;
95 /** @var Conversation */
96 protected $conversation;
97 /** @var IManagePersonalConfigValues */
101 /** @var TimelineFactory */
103 /** @var ChannelFactory */
105 /** @var UserDefinedChannelFactory */
106 protected $userDefinedChannel;
107 /** @var CommunityFactory */
108 protected $community;
109 /** @var NetworkFactory */
110 protected $networkFactory;
112 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 = [])
114 parent::__construct($channel, $mode, $session, $database, $pConfig, $config, $cache, $l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
117 $this->timeline = $timeline;
118 $this->systemMessages = $systemMessages;
119 $this->conversation = $conversation;
121 $this->channel = $channelFactory;
122 $this->community = $community;
123 $this->networkFactory = $network;
124 $this->userDefinedChannel = $userDefinedChannel;
127 protected function content(array $request = []): string
129 if (!$this->session->getLocalUserId()) {
130 return Login::form();
133 $this->parseRequest($request);
137 $arr = ['query' => $this->args->getQueryString()];
138 Hook::callAll('network_content_init', $arr);
142 $this->page['aside'] .= Circle::sidebarWidget($module, $module . '/circle', 'standard', $this->circleId);
143 $this->page['aside'] .= GroupManager::widget($module . '/group', $this->session->getLocalUserId(), $this->groupContactId);
144 $this->page['aside'] .= Widget::postedByYear($module . '/archive', $this->session->getLocalUserId(), false);
145 $this->page['aside'] .= Widget::networks($module, !$this->groupContactId ? $this->network : '');
146 $this->page['aside'] .= Widget::accountTypes($module, $this->accountTypeString);
147 $this->page['aside'] .= Widget::channels($module, $this->selectedTab, $this->session->getLocalUserId());
148 $this->page['aside'] .= Widget\SavedSearches::getHTML($this->args->getQueryString());
149 $this->page['aside'] .= Widget::fileAs('filed', '');
151 if (Feature::isEnabled($this->session->getLocalUserId(), 'trending_tags')) {
152 $this->page['aside'] .= TrendingTags::getHTML($this->selectedTab);
155 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll') && ($_GET['mode'] ?? '') != 'minimal') {
156 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
157 $o .= Renderer::replaceMacros($tpl, ['$reload_uri' => $this->args->getQueryString()]);
160 if (!(isset($_GET['mode']) and ($_GET['mode'] == 'raw'))) {
161 $o .= $this->getTabsHTML();
163 Nav::setSelected($this->args->get(0));
167 if ($this->groupContactId) {
168 // If $this->groupContactId belongs to a community group or a private group, add a mention to the status editor
169 $condition = ["`id` = ? AND `contact-type` = ?", $this->groupContactId, Contact::TYPE_COMMUNITY];
170 $contact = $this->database->selectFirst('contact', ['addr'], $condition);
171 if (!empty($contact['addr'])) {
172 $content = '!' . $contact['addr'];
176 $default_permissions = [];
177 if ($this->circleId) {
178 $default_permissions['allow_gid'] = [$this->circleId];
182 if ($this->groupContactId) {
183 $allowedCids[] = (int) $this->groupContactId;
184 } elseif ($this->network) {
186 'uid' => $this->session->getLocalUserId(),
187 'network' => $this->network,
192 'rel' => [Contact::SHARING, Contact::FRIEND],
194 $contactStmt = $this->database->select('contact', ['id'], $condition);
195 while ($contact = $this->database->fetch($contactStmt)) {
196 $allowedCids[] = (int) $contact['id'];
198 $this->database->close($contactStmt);
201 if (count($allowedCids)) {
202 $default_permissions['allow_cid'] = $allowedCids;
206 'lockstate' => $this->circleId || $this->groupContactId || $this->network || ACL::getLockstateForUserId($this->session->getLocalUserId()) ? 'lock' : 'unlock',
207 'acl' => ACL::getFullSelectorHTML($this->page, $this->session->getLocalUserId(), true, $default_permissions),
208 'bang' => (($this->circleId || $this->groupContactId || $this->network) ? '!' : ''),
209 'content' => $content,
212 $o .= $this->conversation->statusEditor($x);
215 if ($this->circleId) {
216 $circle = $this->database->selectFirst('group', ['name'], ['id' => $this->circleId, 'uid' => $this->session->getLocalUserId()]);
217 if (!$this->database->isResult($circle)) {
218 $this->systemMessages->addNotice($this->l10n->t('No such circle'));
221 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
222 '$title' => $this->l10n->t('Circle: %s', $circle['name'])
224 } elseif ($this->groupContactId) {
225 $contact = Contact::getById($this->groupContactId);
226 if ($this->database->isResult($contact)) {
227 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('contact/list.tpl'), [
228 'contacts' => [ModuleContact::getContactTemplateVars($contact)],
229 'id' => $this->args->get(0),
232 $this->systemMessages->addNotice($this->l10n->t('Invalid contact.'));
234 } elseif (Profile::shouldDisplayEventList($this->session->getLocalUserId(), $this->mode)) {
235 $o .= Profile::getBirthdays($this->session->getLocalUserId());
236 $o .= Profile::getEventsReminderHTML($this->session->getLocalUserId(), $this->session->getPublicContactId());
240 if ($this->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId())) {
241 $items = $this->getChannelItems();
242 } elseif ($this->community->isTimeline($this->selectedTab)) {
243 $items = $this->getCommunityItems();
245 $items = $this->getItems();
248 $o .= $this->conversation->render($items, Conversation::MODE_NETWORK, false, false, $this->getOrder(), $this->session->getLocalUserId());
249 } catch (\Exception $e) {
250 $o .= $this->l10n->t('Error %d (%s) while fetching the timeline.', $e->getCode(), $e->getMessage());
253 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
254 $o .= HTML::scrollLoader();
256 $pager = new BoundariesPager(
258 $this->args->getQueryString(),
259 $items[0][$this->order] ?? null,
260 $items[count($items) - 1][$this->order] ?? null,
264 $o .= $pager->renderMinimal(count($items));
270 protected function getOrder(): string
272 if ($this->order === 'received') {
274 } elseif ($this->order === 'created') {
277 return '`commented`';
282 * Get the network tabs menu
284 * @return string Html of the network tabs
285 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
287 private function getTabsHTML()
289 $tabs = $this->getTabArray($this->networkFactory->getTimelines($this->args->getCommand()), 'network');
291 $network_timelines = $this->pConfig->get($this->session->getLocalUserId(), 'system', 'network_timelines', []);
292 if (!empty($network_timelines)) {
293 $tabs = array_merge($tabs, $this->getTabArray($this->channel->getTimelines($this->session->getLocalUserId()), 'network', 'channel'));
294 $tabs = array_merge($tabs, $this->getTabArray($this->channelRepository->selectByUid($this->session->getLocalUserId()), 'network', 'channel'));
295 $tabs = array_merge($tabs, $this->getTabArray($this->community->getTimelines(true), 'network', 'channel'));
298 $arr = ['tabs' => $tabs];
299 Hook::callAll('network_tabs', $arr);
301 if (!empty($network_timelines)) {
304 foreach ($arr['tabs'] as $tab) {
305 if (in_array($tab['code'], $network_timelines)) {
310 $tabs = $arr['tabs'];
313 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
315 return Renderer::replaceMacros($tpl, ['$tabs' => $tabs]);
318 protected function parseRequest(array $request)
320 parent::parseRequest($request);
322 $this->circleId = (int)($this->parameters['circle_id'] ?? 0);
324 $this->groupContactId = (int)($this->parameters['contact_id'] ?? 0);
326 if (!$this->selectedTab) {
327 $this->selectedTab = self::getTimelineOrderBySession($this->session, $this->pConfig);
328 } elseif (!$this->networkFactory->isTimeline($this->selectedTab) && !$this->channel->isTimeline($this->selectedTab) && !$this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId()) && !$this->community->isTimeline($this->selectedTab)) {
329 throw new HTTPException\BadRequestException($this->l10n->t('Network feed not available.'));
332 if (($this->network || $this->circleId || $this->groupContactId) && ($this->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId()) || $this->community->isTimeline($this->selectedTab))) {
333 $this->selectedTab = NetworkEntity::RECEIVED;
336 if (!empty($request['star'])) {
337 $this->selectedTab = NetworkEntity::STAR;
340 $this->star = $this->selectedTab == NetworkEntity::STAR;
343 if (!empty($request['mention'])) {
344 $this->selectedTab = NetworkEntity::MENTION;
345 $this->mention = true;
347 $this->mention = $this->selectedTab == NetworkEntity::MENTION;
350 if (!empty($request['order'])) {
351 $this->selectedTab = $request['order'];
352 $this->order = $request['order'];
354 $this->mention = false;
355 } elseif (in_array($this->selectedTab, [NetworkEntity::RECEIVED, NetworkEntity::STAR]) || $this->community->isTimeline($this->selectedTab)) {
356 $this->order = 'received';
357 } elseif (($this->selectedTab == NetworkEntity::CREATED) || $this->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId())) {
358 $this->order = 'created';
360 $this->order = 'commented';
363 $this->selectedTab = $this->selectedTab ?? $this->order;
365 // Upon updates in the background and order by last comment we order by received date,
366 // since otherwise the feed will optically jump, when some already visible thread has been updated.
367 if ($this->update && ($this->selectedTab == NetworkEntity::COMMENTED)) {
368 $this->order = 'received';
369 $request['last_received'] = $request['last_commented'] ?? null;
370 $request['first_received'] = $request['first_commented'] ?? null;
373 // Prohibit combined usage of "star" and "mention"
374 if ($this->selectedTab == NetworkEntity::STAR) {
375 $this->mention = false;
376 } elseif ($this->selectedTab == NetworkEntity::MENTION) {
380 $this->session->set('network-tab', $this->selectedTab);
381 $this->pConfig->set($this->session->getLocalUserId(), 'network.view', 'selected_tab', $this->selectedTab);
383 $this->network = $request['nets'] ?? '';
385 $this->dateFrom = $this->parameters['from'] ?? '';
386 $this->dateTo = $this->parameters['to'] ?? '';
388 switch ($this->order) {
390 $this->maxId = $request['last_received'] ?? $this->maxId;
391 $this->minId = $request['first_received'] ?? $this->minId;
394 $this->maxId = $request['last_created'] ?? $this->maxId;
395 $this->minId = $request['first_created'] ?? $this->minId;
398 $this->maxId = $request['last_uriid'] ?? $this->maxId;
399 $this->minId = $request['first_uriid'] ?? $this->minId;
402 $this->order = 'commented';
403 $this->maxId = $request['last_commented'] ?? $this->maxId;
404 $this->minId = $request['first_commented'] ?? $this->minId;
408 protected function getItems()
410 $conditionFields = ['uid' => $this->session->getLocalUserId()];
411 $conditionStrings = [];
413 if (!is_null($this->accountType)) {
414 $conditionFields['contact-type'] = $this->accountType;
418 $conditionFields['starred'] = true;
420 if ($this->mention) {
421 $conditionFields['mention'] = true;
423 if ($this->network) {
424 $conditionFields['network'] = $this->network;
427 if ($this->dateFrom) {
428 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` <= ? ", DateTimeFormat::convert($this->dateFrom, 'UTC', $this->app->getTimeZone())]);
431 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` >= ? ", DateTimeFormat::convert($this->dateTo, 'UTC', $this->app->getTimeZone())]);
434 if ($this->circleId) {
435 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`contact-id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)", $this->circleId]);
436 } elseif ($this->groupContactId) {
437 $conditionStrings = DBA::mergeConditions($conditionStrings,
438 ["((`contact-id` = ?) OR `uri-id` IN (SELECT `parent-uri-id` FROM `post-user-view` WHERE (`contact-id` = ? AND `gravity` = ? AND `vid` = ? AND `uid` = ?)))",
439 $this->groupContactId, $this->groupContactId, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), $this->session->getLocalUserId()]);
442 // Currently only the order modes "received" and "commented" are in use
443 if (!empty($this->itemUriId)) {
444 $conditionStrings = DBA::mergeConditions($conditionStrings, ['uri-id' => $this->itemUriId]);
446 if (isset($this->maxId)) {
447 switch ($this->order) {
449 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` < ?", $this->maxId]);
452 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` < ?", $this->maxId]);
455 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` < ?", $this->maxId]);
458 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` < ?", $this->maxId]);
463 if (isset($this->minId)) {
464 switch ($this->order) {
466 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` > ?", $this->minId]);
469 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` > ?", $this->minId]);
472 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` > ?", $this->minId]);
475 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` > ?", $this->minId]);
481 $params = ['limit' => $this->itemsPerPage];
483 if (isset($this->minId) && !isset($this->maxId)) {
484 // min_id quirk: querying in reverse order with min_id gets the most recent rows, regardless of how close
485 // they are to min_id. We change the query ordering to get the expected data, and we need to reverse the
486 // order of the results.
487 $params['order'] = [$this->order => false];
489 $params['order'] = [$this->order => true];
492 $items = $this->database->selectToArray('network-thread-view', [], DBA::mergeConditions($conditionFields, $conditionStrings), $params);
494 // min_id quirk, continued
495 if (isset($this->minId) && !isset($this->maxId)) {
496 $items = array_reverse($items);
499 if ($this->database->isResult($items)) {
500 $parents = array_column($items, 'uri-id');
505 // We aren't going to try and figure out at the item, circle, and page
506 // level which items you've seen and which you haven't. If you're looking
507 // at the top level network page just mark everything seen.
508 if (!$this->circleId && !$this->groupContactId && !$this->star && !$this->mention) {
509 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId()];
510 $this->setItemsSeenByCondition($condition);
511 } elseif (!empty($parents)) {
512 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => $parents];
513 $this->setItemsSeenByCondition($condition);
520 * Returns the selected network tab of the currently logged-in user
522 * @param IHandleUserSessions $session
523 * @param IManagePersonalConfigValues $pconfig
526 public static function getTimelineOrderBySession(IHandleUserSessions $session, IManagePersonalConfigValues $pconfig): string
528 return $session->get('network-tab')
529 ?? $pconfig->get($session->getLocalUserId(), 'network.view', 'selected_tab')