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::accountTypes($module, $this->accountTypeString);
122 $arr = ['query' => $this->args->getQueryString()];
123 Hook::callAll('network_content_init', $arr);
127 if ($this->timeline->isChannel($this->selectedTab)) {
128 if (!in_array($this->selectedTab, [TimelineEntity::FOLLOWERS, TimelineEntity::FORYOU]) && $this->config->get('system', 'community_no_sharer')) {
129 $this->page['aside'] .= $this->getNoSharerWidget($module);
132 if (Feature::isEnabled($this->session->getLocalUserId(), 'trending_tags')) {
133 $this->page['aside'] .= TrendingTags::getHTML($this->selectedTab);
136 $items = $this->getChannelItems();
137 } elseif ($this->timeline->isCommunity($this->selectedTab)) {
138 if ($this->session->getLocalUserId() && $this->config->get('system', 'community_no_sharer')) {
139 $this->page['aside'] .= $this->getNoSharerWidget($module);
142 if (Feature::isEnabled($this->session->getLocalUserId(), 'trending_tags')) {
143 $this->page['aside'] .= TrendingTags::getHTML($this->selectedTab);
146 $items = $this->getCommunityItems();
148 $this->page['aside'] .= Circle::sidebarWidget($module, $module . '/circle', 'standard', $this->circleId);
149 $this->page['aside'] .= GroupManager::widget($module . '/group', $this->session->getLocalUserId(), $this->groupContactId);
150 $this->page['aside'] .= Widget::postedByYear($module . '/archive', $this->session->getLocalUserId(), false);
151 $this->page['aside'] .= Widget::networks($module, !$this->groupContactId ? $this->network : '');
152 $this->page['aside'] .= Widget\SavedSearches::getHTML($this->args->getQueryString());
153 $this->page['aside'] .= Widget::fileAs('filed', '');
155 $items = $this->getItems();
158 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll') && ($_GET['mode'] ?? '') != 'minimal') {
159 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
160 $o .= Renderer::replaceMacros($tpl, ['$reload_uri' => $this->args->getQueryString()]);
163 if (!(isset($_GET['mode']) and ($_GET['mode'] == 'raw'))) {
164 $o .= $this->getTabsHTML();
166 Nav::setSelected($this->args->get(0));
170 if ($this->groupContactId) {
171 // If $this->groupContactId belongs to a community group or a private group, add a mention to the status editor
172 $condition = ["`id` = ? AND `contact-type` = ?", $this->groupContactId, Contact::TYPE_COMMUNITY];
173 $contact = $this->database->selectFirst('contact', ['addr'], $condition);
174 if (!empty($contact['addr'])) {
175 $content = '!' . $contact['addr'];
179 $default_permissions = [];
180 if ($this->circleId) {
181 $default_permissions['allow_gid'] = [$this->circleId];
185 if ($this->groupContactId) {
186 $allowedCids[] = (int) $this->groupContactId;
187 } elseif ($this->network) {
189 'uid' => $this->session->getLocalUserId(),
190 'network' => $this->network,
195 'rel' => [Contact::SHARING, Contact::FRIEND],
197 $contactStmt = $this->database->select('contact', ['id'], $condition);
198 while ($contact = $this->database->fetch($contactStmt)) {
199 $allowedCids[] = (int) $contact['id'];
201 $this->database->close($contactStmt);
204 if (count($allowedCids)) {
205 $default_permissions['allow_cid'] = $allowedCids;
209 'lockstate' => $this->circleId || $this->groupContactId || $this->network || ACL::getLockstateForUserId($this->session->getLocalUserId()) ? 'lock' : 'unlock',
210 'acl' => ACL::getFullSelectorHTML($this->page, $this->session->getLocalUserId(), true, $default_permissions),
211 'bang' => (($this->circleId || $this->groupContactId || $this->network) ? '!' : ''),
212 'content' => $content,
215 $o .= $this->conversation->statusEditor($x);
218 if ($this->circleId) {
219 $circle = $this->database->selectFirst('group', ['name'], ['id' => $this->circleId, 'uid' => $this->session->getLocalUserId()]);
220 if (!$this->database->isResult($circle)) {
221 $this->systemMessages->addNotice($this->l10n->t('No such circle'));
224 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
225 '$title' => $this->l10n->t('Circle: %s', $circle['name'])
227 } elseif ($this->groupContactId) {
228 $contact = Contact::getById($this->groupContactId);
229 if ($this->database->isResult($contact)) {
230 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('contact/list.tpl'), [
231 'contacts' => [ModuleContact::getContactTemplateVars($contact)],
232 'id' => $this->args->get(0),
235 $this->systemMessages->addNotice($this->l10n->t('Invalid contact.'));
237 } elseif (!$this->config->get('theme', 'hide_eventlist')) {
238 $o .= Profile::getBirthdays();
239 $o .= Profile::getEventsReminderHTML();
242 $o .= $this->conversation->render($items, Conversation::MODE_NETWORK, false, false, $this->getOrder(), $this->session->getLocalUserId());
244 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
245 $o .= HTML::scrollLoader();
247 $pager = new BoundariesPager(
249 $this->args->getQueryString(),
250 $items[0][$this->order] ?? null,
251 $items[count($items) - 1][$this->order] ?? null,
255 $o .= $pager->renderMinimal(count($items));
261 protected function getOrder(): string
263 if ($this->order === 'received') {
265 } elseif ($this->order === 'created') {
268 return '`commented`';
273 * Get the network tabs menu
275 * @return string Html of the network tabs
276 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
278 private function getTabsHTML()
280 // @todo user confgurable selection of tabs
281 $tabs = $this->getTabArray($this->timeline->getNetworkFeeds($this->args->getCommand()), 'network');
283 $network_timelines = $this->pConfig->get($this->session->getLocalUserId(), 'system', 'network_timelines', []);
284 if (!empty($network_timelines)) {
285 $tabs = array_merge($tabs, $this->getTabArray($this->timeline->getChannelsForUser($this->session->getLocalUserId()), 'network', 'channel'));
286 $tabs = array_merge($tabs, $this->getTabArray($this->timeline->getCommunities(true), 'network', 'channel'));
289 $arr = ['tabs' => $tabs];
290 Hook::callAll('network_tabs', $arr);
292 if (!empty($network_timelines)) {
295 foreach (array_keys($arr['tabs']) as $tab) {
296 if (in_array($tab, $network_timelines)) {
297 $tabs[] = $arr['tabs'][$tab];
301 $tabs = $arr['tabs'];
304 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
306 return Renderer::replaceMacros($tpl, ['$tabs' => $tabs]);
309 protected function parseRequest(array $request)
311 parent::parseRequest($request);
313 $this->circleId = (int)($this->parameters['circle_id'] ?? 0);
315 $this->groupContactId = (int)($this->parameters['contact_id'] ?? 0);
317 if (!$this->selectedTab) {
318 $this->selectedTab = self::getTimelineOrderBySession($this->session, $this->pConfig);
319 } elseif (!$this->timeline->isChannel($this->selectedTab) && !$this->timeline->isCommunity($this->selectedTab)) {
320 throw new HTTPException\BadRequestException($this->l10n->t('Network feed not available.'));
323 if (!empty($request['star'])) {
324 $this->selectedTab = TimelineEntity::STAR;
327 $this->star = $this->selectedTab == TimelineEntity::STAR;
330 if (!empty($request['mention'])) {
331 $this->selectedTab = TimelineEntity::MENTION;
332 $this->mention = true;
334 $this->mention = $this->selectedTab == TimelineEntity::MENTION;
337 if (!empty($request['order'])) {
338 $this->selectedTab = $request['order'];
339 $this->order = $request['order'];
341 $this->mention = false;
342 } elseif (in_array($this->selectedTab, [TimelineEntity::RECEIVED, TimelineEntity::STAR])) {
343 $this->order = 'received';
344 } elseif (($this->selectedTab == TimelineEntity::CREATED) || $this->timeline->isChannel($this->selectedTab)) {
345 $this->order = 'created';
347 $this->order = 'commented';
350 $this->selectedTab = $this->selectedTab ?? $this->order;
352 // Prohibit combined usage of "star" and "mention"
353 if ($this->selectedTab == TimelineEntity::STAR) {
354 $this->mention = false;
355 } elseif ($this->selectedTab == TimelineEntity::MENTION) {
359 $this->session->set('network-tab', $this->selectedTab);
360 $this->pConfig->set($this->session->getLocalUserId(), 'network.view', 'selected_tab', $this->selectedTab);
362 $this->network = $request['nets'] ?? '';
364 $this->dateFrom = $this->parameters['from'] ?? '';
365 $this->dateTo = $this->parameters['to'] ?? '';
367 switch ($this->order) {
369 $this->maxId = $request['last_received'] ?? $this->maxId;
372 $this->maxId = $request['last_created'] ?? $this->maxId;
375 $this->maxId = $request['last_uriid'] ?? $this->maxId;
378 $this->order = 'commented';
379 $this->maxId = $request['last_commented'] ?? $this->maxId;
383 protected function getItems()
385 $conditionFields = ['uid' => $this->session->getLocalUserId()];
386 $conditionStrings = [];
388 if (!is_null($this->accountType)) {
389 $conditionFields['contact-type'] = $this->accountType;
393 $conditionFields['starred'] = true;
395 if ($this->mention) {
396 $conditionFields['mention'] = true;
398 if ($this->network) {
399 $conditionFields['network'] = $this->network;
402 if ($this->dateFrom) {
403 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` <= ? ", DateTimeFormat::convert($this->dateFrom, 'UTC', $this->app->getTimeZone())]);
406 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` >= ? ", DateTimeFormat::convert($this->dateTo, 'UTC', $this->app->getTimeZone())]);
409 if ($this->circleId) {
410 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`contact-id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)", $this->circleId]);
411 } elseif ($this->groupContactId) {
412 $conditionStrings = DBA::mergeConditions($conditionStrings,
413 ["((`contact-id` = ?) OR `uri-id` IN (SELECT `parent-uri-id` FROM `post-user-view` WHERE (`contact-id` = ? AND `gravity` = ? AND `vid` = ? AND `uid` = ?)))",
414 $this->groupContactId, $this->groupContactId, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), $this->session->getLocalUserId()]);
417 // Currently only the order modes "received" and "commented" are in use
418 if (!empty($this->itemUriId)) {
419 $conditionStrings = DBA::mergeConditions($conditionStrings, ['uri-id' => $this->itemUriId]);
421 if (isset($this->maxId)) {
422 switch ($this->order) {
424 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` < ?", $this->maxId]);
427 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` < ?", $this->maxId]);
430 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` < ?", $this->maxId]);
433 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` < ?", $this->maxId]);
438 if (isset($this->minId)) {
439 switch ($this->order) {
441 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` > ?", $this->minId]);
444 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` > ?", $this->minId]);
447 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` > ?", $this->minId]);
450 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` > ?", $this->minId]);
456 $params = ['limit' => $this->itemsPerPage];
458 if (isset($this->minId) && !isset($this->maxId)) {
459 // min_id quirk: querying in reverse order with min_id gets the most recent rows, regardless of how close
460 // they are to min_id. We change the query ordering to get the expected data, and we need to reverse the
461 // order of the results.
462 $params['order'] = [$this->order => false];
464 $params['order'] = [$this->order => true];
467 $items = $this->database->selectToArray('network-thread-view', [], DBA::mergeConditions($conditionFields, $conditionStrings), $params);
469 // min_id quirk, continued
470 if (isset($this->minId) && !isset($this->maxId)) {
471 $items = array_reverse($items);
474 if ($this->database->isResult($items)) {
475 $parents = array_column($items, 'uri-id');
480 // We aren't going to try and figure out at the item, circle, and page
481 // level which items you've seen and which you haven't. If you're looking
482 // at the top level network page just mark everything seen.
483 if (!$this->circleId && !$this->groupContactId && !$this->star && !$this->mention) {
484 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId()];
485 $this->setItemsSeenByCondition($condition);
486 } elseif (!empty($parents)) {
487 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => $parents];
488 $this->setItemsSeenByCondition($condition);
495 * Returns the selected network tab of the currently logged-in user
497 * @param IHandleUserSessions $session
498 * @param IManagePersonalConfigValues $pconfig
501 public static function getTimelineOrderBySession(IHandleUserSessions $session, IManagePersonalConfigValues $pconfig): string
503 return $session->get('network-tab')
504 ?? $pconfig->get($session->getLocalUserId(), 'network.view', 'selected_tab')