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\Timeline as TimelineEntity;
29 use Friendica\Content\Conversation\Factory\Timeline as TimelineFactory;
30 use Friendica\Content\Feature;
31 use Friendica\Content\GroupManager;
32 use Friendica\Content\Nav;
33 use Friendica\Content\Widget;
34 use Friendica\Content\Text\HTML;
35 use Friendica\Content\Widget\TrendingTags;
36 use Friendica\Core\ACL;
37 use Friendica\Core\Cache\Capability\ICanCache;
38 use Friendica\Core\Config\Capability\IManageConfigValues;
39 use Friendica\Core\Hook;
40 use Friendica\Core\L10n;
41 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
42 use Friendica\Core\Renderer;
43 use Friendica\Core\Session\Capability\IHandleUserSessions;
44 use Friendica\Database\DBA;
45 use Friendica\Database\Database;
46 use Friendica\Model\Contact;
47 use Friendica\Model\Circle;
48 use Friendica\Model\Item;
49 use Friendica\Model\Profile;
50 use Friendica\Model\Verb;
51 use Friendica\Module\Contact as ModuleContact;
52 use Friendica\Module\Response;
53 use Friendica\Module\Security\Login;
54 use Friendica\Network\HTTPException;
55 use Friendica\Navigation\SystemMessages;
56 use Friendica\Util\DateTimeFormat;
57 use Friendica\Util\Profiler;
58 use Friendica\Protocol\Activity;
59 use Psr\Log\LoggerInterface;
61 class Network extends Timeline
66 protected $groupContactId;
84 /** @var IManageConfigValues The config */
86 /** @var SystemMessages */
87 protected $systemMessages;
90 /** @var Conversation */
91 protected $conversation;
92 /** @var IManagePersonalConfigValues */
96 /** @var TimelineFactory */
99 public function __construct(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 = [])
101 parent::__construct($mode, $session, $database, $pConfig, $config, $cache, $l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
104 $this->timeline = $timeline;
105 $this->systemMessages = $systemMessages;
106 $this->conversation = $conversation;
110 protected function content(array $request = []): string
112 if (!$this->session->getLocalUserId()) {
113 return Login::form();
116 $this->parseRequest($request);
120 $this->page['aside'] .= Widget::channels($module, $this->selectedTab, $this->session->getLocalUserId());
121 $this->page['aside'] .= Widget::accountTypes($module, $this->accountTypeString);
123 $arr = ['query' => $this->args->getQueryString()];
124 Hook::callAll('network_content_init', $arr);
128 if ($this->timeline->isChannel($this->selectedTab)) {
129 if (!in_array($this->selectedTab, [TimelineEntity::FOLLOWERS, TimelineEntity::FORYOU]) && $this->config->get('system', 'community_no_sharer')) {
130 $this->page['aside'] .= $this->getNoSharerWidget($module);
133 if (Feature::isEnabled($this->session->getLocalUserId(), 'trending_tags')) {
134 $this->page['aside'] .= TrendingTags::getHTML($this->selectedTab);
137 $items = $this->getChannelItems();
138 } elseif ($this->timeline->isCommunity($this->selectedTab)) {
139 if ($this->session->getLocalUserId() && $this->config->get('system', 'community_no_sharer')) {
140 $this->page['aside'] .= $this->getNoSharerWidget($module);
143 if (Feature::isEnabled($this->session->getLocalUserId(), 'trending_tags')) {
144 $this->page['aside'] .= TrendingTags::getHTML($this->selectedTab);
147 $items = $this->getCommunityItems();
149 $this->page['aside'] .= Circle::sidebarWidget($module, $module . '/circle', 'standard', $this->circleId);
150 $this->page['aside'] .= GroupManager::widget($module . '/group', $this->session->getLocalUserId(), $this->groupContactId);
151 $this->page['aside'] .= Widget::postedByYear($module . '/archive', $this->session->getLocalUserId(), false);
152 $this->page['aside'] .= Widget::networks($module, !$this->groupContactId ? $this->network : '');
153 $this->page['aside'] .= Widget\SavedSearches::getHTML($this->args->getQueryString());
154 $this->page['aside'] .= Widget::fileAs('filed', '');
156 $items = $this->getItems();
159 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll') && ($_GET['mode'] ?? '') != 'minimal') {
160 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
161 $o .= Renderer::replaceMacros($tpl, ['$reload_uri' => $this->args->getQueryString()]);
164 if (!(isset($_GET['mode']) and ($_GET['mode'] == 'raw'))) {
165 $o .= $this->getTabsHTML();
167 Nav::setSelected($this->args->get(0));
171 if ($this->groupContactId) {
172 // If $this->groupContactId belongs to a community group or a private group, add a mention to the status editor
173 $condition = ["`id` = ? AND `contact-type` = ?", $this->groupContactId, Contact::TYPE_COMMUNITY];
174 $contact = $this->database->selectFirst('contact', ['addr'], $condition);
175 if (!empty($contact['addr'])) {
176 $content = '!' . $contact['addr'];
180 $default_permissions = [];
181 if ($this->circleId) {
182 $default_permissions['allow_gid'] = [$this->circleId];
186 if ($this->groupContactId) {
187 $allowedCids[] = (int) $this->groupContactId;
188 } elseif ($this->network) {
190 'uid' => $this->session->getLocalUserId(),
191 'network' => $this->network,
196 'rel' => [Contact::SHARING, Contact::FRIEND],
198 $contactStmt = $this->database->select('contact', ['id'], $condition);
199 while ($contact = $this->database->fetch($contactStmt)) {
200 $allowedCids[] = (int) $contact['id'];
202 $this->database->close($contactStmt);
205 if (count($allowedCids)) {
206 $default_permissions['allow_cid'] = $allowedCids;
210 'lockstate' => $this->circleId || $this->groupContactId || $this->network || ACL::getLockstateForUserId($this->session->getLocalUserId()) ? 'lock' : 'unlock',
211 'acl' => ACL::getFullSelectorHTML($this->page, $this->session->getLocalUserId(), true, $default_permissions),
212 'bang' => (($this->circleId || $this->groupContactId || $this->network) ? '!' : ''),
213 'content' => $content,
216 $o .= $this->conversation->statusEditor($x);
219 if ($this->circleId) {
220 $circle = $this->database->selectFirst('group', ['name'], ['id' => $this->circleId, 'uid' => $this->session->getLocalUserId()]);
221 if (!$this->database->isResult($circle)) {
222 $this->systemMessages->addNotice($this->l10n->t('No such circle'));
225 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
226 '$title' => $this->l10n->t('Circle: %s', $circle['name'])
228 } elseif ($this->groupContactId) {
229 $contact = Contact::getById($this->groupContactId);
230 if ($this->database->isResult($contact)) {
231 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('contact/list.tpl'), [
232 'contacts' => [ModuleContact::getContactTemplateVars($contact)],
233 'id' => $this->args->get(0),
236 $this->systemMessages->addNotice($this->l10n->t('Invalid contact.'));
238 } elseif (!$this->config->get('theme', 'hide_eventlist')) {
239 $o .= Profile::getBirthdays();
240 $o .= Profile::getEventsReminderHTML();
243 $o .= $this->conversation->render($items, Conversation::MODE_NETWORK, false, false, $this->getOrder(), $this->session->getLocalUserId());
245 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
246 $o .= HTML::scrollLoader();
248 $pager = new BoundariesPager(
250 $this->args->getQueryString(),
251 $items[0][$this->order] ?? null,
252 $items[count($items) - 1][$this->order] ?? null,
256 $o .= $pager->renderMinimal(count($items));
262 protected function getOrder(): string
264 if ($this->order === 'received') {
266 } elseif ($this->order === 'created') {
269 return '`commented`';
274 * Get the network tabs menu
276 * @return string Html of the network tabs
277 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
279 private function getTabsHTML()
281 // @todo user confgurable selection of tabs
282 $tabs = $this->getTabArray($this->timeline->getNetworkFeeds($this->args->getCommand()), 'network');
284 $network_timelines = $this->pConfig->get($this->session->getLocalUserId(), 'system', 'network_timelines', []);
285 if (!empty($network_timelines)) {
286 $tabs = array_merge($tabs, $this->getTabArray($this->timeline->getChannelsForUser($this->session->getLocalUserId()), 'network', 'channel'));
287 $tabs = array_merge($tabs, $this->getTabArray($this->timeline->getCommunities(true), 'network', 'channel'));
290 $arr = ['tabs' => $tabs];
291 Hook::callAll('network_tabs', $arr);
293 if (!empty($network_timelines)) {
296 foreach (array_keys($arr['tabs']) as $tab) {
297 if (in_array($tab, $network_timelines)) {
298 $tabs[] = $arr['tabs'][$tab];
302 $tabs = $arr['tabs'];
305 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
307 return Renderer::replaceMacros($tpl, ['$tabs' => $tabs]);
310 protected function parseRequest(array $request)
312 parent::parseRequest($request);
314 $this->circleId = (int)($this->parameters['circle_id'] ?? 0);
316 $this->groupContactId = (int)($this->parameters['contact_id'] ?? 0);
318 if (!$this->selectedTab) {
319 $this->selectedTab = self::getTimelineOrderBySession($this->session, $this->pConfig);
320 } elseif (!$this->timeline->isChannel($this->selectedTab) && !$this->timeline->isCommunity($this->selectedTab)) {
321 throw new HTTPException\BadRequestException($this->l10n->t('Network feed not available.'));
324 if (!empty($request['star'])) {
325 $this->selectedTab = TimelineEntity::STAR;
328 $this->star = $this->selectedTab == TimelineEntity::STAR;
331 if (!empty($request['mention'])) {
332 $this->selectedTab = TimelineEntity::MENTION;
333 $this->mention = true;
335 $this->mention = $this->selectedTab == TimelineEntity::MENTION;
338 if (!empty($request['order'])) {
339 $this->selectedTab = $request['order'];
340 $this->order = $request['order'];
342 $this->mention = false;
343 } elseif (in_array($this->selectedTab, [TimelineEntity::RECEIVED, TimelineEntity::STAR]) || $this->timeline->isCommunity($this->selectedTab)) {
344 $this->order = 'received';
345 } elseif (($this->selectedTab == TimelineEntity::CREATED) || $this->timeline->isChannel($this->selectedTab)) {
346 $this->order = 'created';
348 $this->order = 'commented';
351 // Upon force (updates in the background) and order by last comment we order by receive date,
352 // since otherwise the feed will optically jump, when some already visible thread has been updated.
353 if ($this->force && ($this->selectedTab == TimelineEntity::COMMENTED) && !empty($request['first_commented'])) {
354 $this->order = 'received';
357 $this->selectedTab = $this->selectedTab ?? $this->order;
359 // Prohibit combined usage of "star" and "mention"
360 if ($this->selectedTab == TimelineEntity::STAR) {
361 $this->mention = false;
362 } elseif ($this->selectedTab == TimelineEntity::MENTION) {
366 $this->session->set('network-tab', $this->selectedTab);
367 $this->pConfig->set($this->session->getLocalUserId(), 'network.view', 'selected_tab', $this->selectedTab);
369 $this->network = $request['nets'] ?? '';
371 $this->dateFrom = $this->parameters['from'] ?? '';
372 $this->dateTo = $this->parameters['to'] ?? '';
374 switch ($this->order) {
376 $this->maxId = $request['last_received'] ?? $this->maxId;
377 $this->minId = $request['first_received'] ?? $this->minId;
380 $this->maxId = $request['last_created'] ?? $this->maxId;
381 $this->minId = $request['first_created'] ?? $this->minId;
384 $this->maxId = $request['last_uriid'] ?? $this->maxId;
385 $this->minId = $request['first_uriid'] ?? $this->minId;
388 $this->order = 'commented';
389 $this->maxId = $request['last_commented'] ?? $this->maxId;
390 $this->minId = $request['first_commented'] ?? $this->minId;
394 protected function getItems()
396 $conditionFields = ['uid' => $this->session->getLocalUserId()];
397 $conditionStrings = [];
399 if (!is_null($this->accountType)) {
400 $conditionFields['contact-type'] = $this->accountType;
404 $conditionFields['starred'] = true;
406 if ($this->mention) {
407 $conditionFields['mention'] = true;
409 if ($this->network) {
410 $conditionFields['network'] = $this->network;
413 if ($this->dateFrom) {
414 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` <= ? ", DateTimeFormat::convert($this->dateFrom, 'UTC', $this->app->getTimeZone())]);
417 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` >= ? ", DateTimeFormat::convert($this->dateTo, 'UTC', $this->app->getTimeZone())]);
420 if ($this->circleId) {
421 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`contact-id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)", $this->circleId]);
422 } elseif ($this->groupContactId) {
423 $conditionStrings = DBA::mergeConditions($conditionStrings,
424 ["((`contact-id` = ?) OR `uri-id` IN (SELECT `parent-uri-id` FROM `post-user-view` WHERE (`contact-id` = ? AND `gravity` = ? AND `vid` = ? AND `uid` = ?)))",
425 $this->groupContactId, $this->groupContactId, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), $this->session->getLocalUserId()]);
428 // Currently only the order modes "received" and "commented" are in use
429 if (!empty($this->itemUriId)) {
430 $conditionStrings = DBA::mergeConditions($conditionStrings, ['uri-id' => $this->itemUriId]);
432 if (isset($this->maxId)) {
433 switch ($this->order) {
435 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` < ?", $this->maxId]);
438 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` < ?", $this->maxId]);
441 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` < ?", $this->maxId]);
444 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` < ?", $this->maxId]);
449 if (isset($this->minId)) {
450 switch ($this->order) {
452 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` > ?", $this->minId]);
455 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` > ?", $this->minId]);
458 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` > ?", $this->minId]);
461 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` > ?", $this->minId]);
467 $params = ['limit' => $this->itemsPerPage];
469 if (isset($this->minId) && !isset($this->maxId)) {
470 // min_id quirk: querying in reverse order with min_id gets the most recent rows, regardless of how close
471 // they are to min_id. We change the query ordering to get the expected data, and we need to reverse the
472 // order of the results.
473 $params['order'] = [$this->order => false];
475 $params['order'] = [$this->order => true];
478 $items = $this->database->selectToArray('network-thread-view', [], DBA::mergeConditions($conditionFields, $conditionStrings), $params);
480 // min_id quirk, continued
481 if (isset($this->minId) && !isset($this->maxId)) {
482 $items = array_reverse($items);
485 if ($this->database->isResult($items)) {
486 $parents = array_column($items, 'uri-id');
491 // We aren't going to try and figure out at the item, circle, and page
492 // level which items you've seen and which you haven't. If you're looking
493 // at the top level network page just mark everything seen.
494 if (!$this->circleId && !$this->groupContactId && !$this->star && !$this->mention) {
495 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId()];
496 $this->setItemsSeenByCondition($condition);
497 } elseif (!empty($parents)) {
498 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => $parents];
499 $this->setItemsSeenByCondition($condition);
506 * Returns the selected network tab of the currently logged-in user
508 * @param IHandleUserSessions $session
509 * @param IManagePersonalConfigValues $pconfig
512 public static function getTimelineOrderBySession(IHandleUserSessions $session, IManagePersonalConfigValues $pconfig): string
514 return $session->get('network-tab')
515 ?? $pconfig->get($session->getLocalUserId(), 'network.view', 'selected_tab')