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\Conversation\Repository\Channel;
31 use Friendica\Content\Feature;
32 use Friendica\Content\GroupManager;
33 use Friendica\Content\Nav;
34 use Friendica\Content\Widget;
35 use Friendica\Content\Text\HTML;
36 use Friendica\Content\Widget\TrendingTags;
37 use Friendica\Core\ACL;
38 use Friendica\Core\Cache\Capability\ICanCache;
39 use Friendica\Core\Config\Capability\IManageConfigValues;
40 use Friendica\Core\Hook;
41 use Friendica\Core\L10n;
42 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
43 use Friendica\Core\Renderer;
44 use Friendica\Core\Session\Capability\IHandleUserSessions;
45 use Friendica\Database\DBA;
46 use Friendica\Database\Database;
47 use Friendica\Model\Contact;
48 use Friendica\Model\Circle;
49 use Friendica\Model\Item;
50 use Friendica\Model\Profile;
51 use Friendica\Model\Verb;
52 use Friendica\Module\Contact as ModuleContact;
53 use Friendica\Module\Response;
54 use Friendica\Module\Security\Login;
55 use Friendica\Network\HTTPException;
56 use Friendica\Navigation\SystemMessages;
57 use Friendica\Util\DateTimeFormat;
58 use Friendica\Util\Profiler;
59 use Friendica\Protocol\Activity;
60 use Psr\Log\LoggerInterface;
62 class Network extends Timeline
67 protected $groupContactId;
85 /** @var IManageConfigValues The config */
87 /** @var SystemMessages */
88 protected $systemMessages;
91 /** @var Conversation */
92 protected $conversation;
93 /** @var IManagePersonalConfigValues */
97 /** @var TimelineFactory */
100 public function __construct(Channel $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 = [])
102 parent::__construct($channel, $mode, $session, $database, $pConfig, $config, $cache, $l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
105 $this->timeline = $timeline;
106 $this->systemMessages = $systemMessages;
107 $this->conversation = $conversation;
111 protected function content(array $request = []): string
113 if (!$this->session->getLocalUserId()) {
114 return Login::form();
117 $this->parseRequest($request);
121 $arr = ['query' => $this->args->getQueryString()];
122 Hook::callAll('network_content_init', $arr);
126 if ($this->timeline->isChannel($this->selectedTab, $this->session->getLocalUserId())) {
127 $items = $this->getChannelItems();
128 } elseif ($this->timeline->isCommunity($this->selectedTab)) {
129 $items = $this->getCommunityItems();
131 $items = $this->getItems();
134 $this->page['aside'] .= Circle::sidebarWidget($module, $module . '/circle', 'standard', $this->circleId);
135 $this->page['aside'] .= GroupManager::widget($module . '/group', $this->session->getLocalUserId(), $this->groupContactId);
136 $this->page['aside'] .= Widget::postedByYear($module . '/archive', $this->session->getLocalUserId(), false);
137 $this->page['aside'] .= Widget::networks($module, !$this->groupContactId ? $this->network : '');
138 $this->page['aside'] .= Widget::accountTypes($module, $this->accountTypeString);
139 $this->page['aside'] .= Widget::channels($module, $this->selectedTab, $this->session->getLocalUserId());
140 $this->page['aside'] .= Widget\SavedSearches::getHTML($this->args->getQueryString());
141 $this->page['aside'] .= Widget::fileAs('filed', '');
143 if (Feature::isEnabled($this->session->getLocalUserId(), 'trending_tags')) {
144 $this->page['aside'] .= TrendingTags::getHTML($this->selectedTab);
147 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll') && ($_GET['mode'] ?? '') != 'minimal') {
148 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
149 $o .= Renderer::replaceMacros($tpl, ['$reload_uri' => $this->args->getQueryString()]);
152 if (!(isset($_GET['mode']) and ($_GET['mode'] == 'raw'))) {
153 $o .= $this->getTabsHTML();
155 Nav::setSelected($this->args->get(0));
159 if ($this->groupContactId) {
160 // If $this->groupContactId belongs to a community group or a private group, add a mention to the status editor
161 $condition = ["`id` = ? AND `contact-type` = ?", $this->groupContactId, Contact::TYPE_COMMUNITY];
162 $contact = $this->database->selectFirst('contact', ['addr'], $condition);
163 if (!empty($contact['addr'])) {
164 $content = '!' . $contact['addr'];
168 $default_permissions = [];
169 if ($this->circleId) {
170 $default_permissions['allow_gid'] = [$this->circleId];
174 if ($this->groupContactId) {
175 $allowedCids[] = (int) $this->groupContactId;
176 } elseif ($this->network) {
178 'uid' => $this->session->getLocalUserId(),
179 'network' => $this->network,
184 'rel' => [Contact::SHARING, Contact::FRIEND],
186 $contactStmt = $this->database->select('contact', ['id'], $condition);
187 while ($contact = $this->database->fetch($contactStmt)) {
188 $allowedCids[] = (int) $contact['id'];
190 $this->database->close($contactStmt);
193 if (count($allowedCids)) {
194 $default_permissions['allow_cid'] = $allowedCids;
198 'lockstate' => $this->circleId || $this->groupContactId || $this->network || ACL::getLockstateForUserId($this->session->getLocalUserId()) ? 'lock' : 'unlock',
199 'acl' => ACL::getFullSelectorHTML($this->page, $this->session->getLocalUserId(), true, $default_permissions),
200 'bang' => (($this->circleId || $this->groupContactId || $this->network) ? '!' : ''),
201 'content' => $content,
204 $o .= $this->conversation->statusEditor($x);
207 if ($this->circleId) {
208 $circle = $this->database->selectFirst('group', ['name'], ['id' => $this->circleId, 'uid' => $this->session->getLocalUserId()]);
209 if (!$this->database->isResult($circle)) {
210 $this->systemMessages->addNotice($this->l10n->t('No such circle'));
213 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
214 '$title' => $this->l10n->t('Circle: %s', $circle['name'])
216 } elseif ($this->groupContactId) {
217 $contact = Contact::getById($this->groupContactId);
218 if ($this->database->isResult($contact)) {
219 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('contact/list.tpl'), [
220 'contacts' => [ModuleContact::getContactTemplateVars($contact)],
221 'id' => $this->args->get(0),
224 $this->systemMessages->addNotice($this->l10n->t('Invalid contact.'));
226 } elseif (!$this->config->get('theme', 'hide_eventlist')) {
227 $o .= Profile::getBirthdays();
228 $o .= Profile::getEventsReminderHTML();
231 $o .= $this->conversation->render($items, Conversation::MODE_NETWORK, false, false, $this->getOrder(), $this->session->getLocalUserId());
233 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
234 $o .= HTML::scrollLoader();
236 $pager = new BoundariesPager(
238 $this->args->getQueryString(),
239 $items[0][$this->order] ?? null,
240 $items[count($items) - 1][$this->order] ?? null,
244 $o .= $pager->renderMinimal(count($items));
250 protected function getOrder(): string
252 if ($this->order === 'received') {
254 } elseif ($this->order === 'created') {
257 return '`commented`';
262 * Get the network tabs menu
264 * @return string Html of the network tabs
265 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
267 private function getTabsHTML()
269 $tabs = $this->getTabArray($this->timeline->getNetworkFeeds($this->args->getCommand()), 'network');
271 $network_timelines = $this->pConfig->get($this->session->getLocalUserId(), 'system', 'network_timelines', []);
272 if (!empty($network_timelines)) {
273 $tabs = array_merge($tabs, $this->getTabArray($this->timeline->getChannelsForUser($this->session->getLocalUserId()), 'network', 'channel'));
274 $tabs = array_merge($tabs, $this->getTabArray($this->timeline->getCommunities(true), 'network', 'channel'));
277 $arr = ['tabs' => $tabs];
278 Hook::callAll('network_tabs', $arr);
280 if (!empty($network_timelines)) {
283 foreach ($arr['tabs'] as $tab) {
284 if (in_array($tab['code'], $network_timelines)) {
289 $tabs = $arr['tabs'];
292 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
294 return Renderer::replaceMacros($tpl, ['$tabs' => $tabs]);
297 protected function parseRequest(array $request)
299 parent::parseRequest($request);
301 $this->circleId = (int)($this->parameters['circle_id'] ?? 0);
303 $this->groupContactId = (int)($this->parameters['contact_id'] ?? 0);
305 if (!$this->selectedTab) {
306 $this->selectedTab = self::getTimelineOrderBySession($this->session, $this->pConfig);
307 } elseif (!$this->timeline->isNetwork($this->selectedTab) && !$this->timeline->isChannel($this->selectedTab, $this->session->getLocalUserId()) && !$this->timeline->isCommunity($this->selectedTab)) {
308 throw new HTTPException\BadRequestException($this->l10n->t('Network feed not available.'));
311 if (($this->network || $this->circleId || $this->groupContactId) && ($this->timeline->isChannel($this->selectedTab, $this->session->getLocalUserId()) || $this->timeline->isCommunity($this->selectedTab))) {
312 $this->selectedTab = TimelineEntity::RECEIVED;
315 if (!empty($request['star'])) {
316 $this->selectedTab = TimelineEntity::STAR;
319 $this->star = $this->selectedTab == TimelineEntity::STAR;
322 if (!empty($request['mention'])) {
323 $this->selectedTab = TimelineEntity::MENTION;
324 $this->mention = true;
326 $this->mention = $this->selectedTab == TimelineEntity::MENTION;
329 if (!empty($request['order'])) {
330 $this->selectedTab = $request['order'];
331 $this->order = $request['order'];
333 $this->mention = false;
334 } elseif (in_array($this->selectedTab, [TimelineEntity::RECEIVED, TimelineEntity::STAR]) || $this->timeline->isCommunity($this->selectedTab)) {
335 $this->order = 'received';
336 } elseif (($this->selectedTab == TimelineEntity::CREATED) || $this->timeline->isChannel($this->selectedTab, $this->session->getLocalUserId())) {
337 $this->order = 'created';
339 $this->order = 'commented';
342 $this->selectedTab = $this->selectedTab ?? $this->order;
344 // Upon updates in the background and order by last comment we order by received date,
345 // since otherwise the feed will optically jump, when some already visible thread has been updated.
346 if ($this->update && ($this->selectedTab == TimelineEntity::COMMENTED)) {
347 $this->order = 'received';
348 $request['last_received'] = $request['last_commented'] ?? null;
349 $request['first_received'] = $request['first_commented'] ?? null;
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;
370 $this->minId = $request['first_received'] ?? $this->minId;
373 $this->maxId = $request['last_created'] ?? $this->maxId;
374 $this->minId = $request['first_created'] ?? $this->minId;
377 $this->maxId = $request['last_uriid'] ?? $this->maxId;
378 $this->minId = $request['first_uriid'] ?? $this->minId;
381 $this->order = 'commented';
382 $this->maxId = $request['last_commented'] ?? $this->maxId;
383 $this->minId = $request['first_commented'] ?? $this->minId;
387 protected function getItems()
389 $conditionFields = ['uid' => $this->session->getLocalUserId()];
390 $conditionStrings = [];
392 if (!is_null($this->accountType)) {
393 $conditionFields['contact-type'] = $this->accountType;
397 $conditionFields['starred'] = true;
399 if ($this->mention) {
400 $conditionFields['mention'] = true;
402 if ($this->network) {
403 $conditionFields['network'] = $this->network;
406 if ($this->dateFrom) {
407 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` <= ? ", DateTimeFormat::convert($this->dateFrom, 'UTC', $this->app->getTimeZone())]);
410 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` >= ? ", DateTimeFormat::convert($this->dateTo, 'UTC', $this->app->getTimeZone())]);
413 if ($this->circleId) {
414 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`contact-id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)", $this->circleId]);
415 } elseif ($this->groupContactId) {
416 $conditionStrings = DBA::mergeConditions($conditionStrings,
417 ["((`contact-id` = ?) OR `uri-id` IN (SELECT `parent-uri-id` FROM `post-user-view` WHERE (`contact-id` = ? AND `gravity` = ? AND `vid` = ? AND `uid` = ?)))",
418 $this->groupContactId, $this->groupContactId, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), $this->session->getLocalUserId()]);
421 // Currently only the order modes "received" and "commented" are in use
422 if (!empty($this->itemUriId)) {
423 $conditionStrings = DBA::mergeConditions($conditionStrings, ['uri-id' => $this->itemUriId]);
425 if (isset($this->maxId)) {
426 switch ($this->order) {
428 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` < ?", $this->maxId]);
431 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` < ?", $this->maxId]);
434 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` < ?", $this->maxId]);
437 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` < ?", $this->maxId]);
442 if (isset($this->minId)) {
443 switch ($this->order) {
445 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` > ?", $this->minId]);
448 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` > ?", $this->minId]);
451 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` > ?", $this->minId]);
454 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` > ?", $this->minId]);
460 $params = ['limit' => $this->itemsPerPage];
462 if (isset($this->minId) && !isset($this->maxId)) {
463 // min_id quirk: querying in reverse order with min_id gets the most recent rows, regardless of how close
464 // they are to min_id. We change the query ordering to get the expected data, and we need to reverse the
465 // order of the results.
466 $params['order'] = [$this->order => false];
468 $params['order'] = [$this->order => true];
471 $items = $this->database->selectToArray('network-thread-view', [], DBA::mergeConditions($conditionFields, $conditionStrings), $params);
473 // min_id quirk, continued
474 if (isset($this->minId) && !isset($this->maxId)) {
475 $items = array_reverse($items);
478 if ($this->database->isResult($items)) {
479 $parents = array_column($items, 'uri-id');
484 // We aren't going to try and figure out at the item, circle, and page
485 // level which items you've seen and which you haven't. If you're looking
486 // at the top level network page just mark everything seen.
487 if (!$this->circleId && !$this->groupContactId && !$this->star && !$this->mention) {
488 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId()];
489 $this->setItemsSeenByCondition($condition);
490 } elseif (!empty($parents)) {
491 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => $parents];
492 $this->setItemsSeenByCondition($condition);
499 * Returns the selected network tab of the currently logged-in user
501 * @param IHandleUserSessions $session
502 * @param IManagePersonalConfigValues $pconfig
505 public static function getTimelineOrderBySession(IHandleUserSessions $session, IManagePersonalConfigValues $pconfig): string
507 return $session->get('network-tab')
508 ?? $pconfig->get($session->getLocalUserId(), 'network.view', 'selected_tab')