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\Channel;
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 */
104 protected $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, 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 = [])
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->channelFactory = $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 if ($this->channelFactory->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId())) {
143 $items = $this->getChannelItems();
144 } elseif ($this->community->isTimeline($this->selectedTab)) {
145 $items = $this->getCommunityItems();
147 $items = $this->getItems();
150 $this->page['aside'] .= Circle::sidebarWidget($module, $module . '/circle', 'standard', $this->circleId);
151 $this->page['aside'] .= GroupManager::widget($module . '/group', $this->session->getLocalUserId(), $this->groupContactId);
152 $this->page['aside'] .= Widget::postedByYear($module . '/archive', $this->session->getLocalUserId(), false);
153 $this->page['aside'] .= Widget::networks($module, !$this->groupContactId ? $this->network : '');
154 $this->page['aside'] .= Widget::accountTypes($module, $this->accountTypeString);
155 $this->page['aside'] .= Widget::channels($module, $this->selectedTab, $this->session->getLocalUserId());
156 $this->page['aside'] .= Widget\SavedSearches::getHTML($this->args->getQueryString());
157 $this->page['aside'] .= Widget::fileAs('filed', '');
159 if (Feature::isEnabled($this->session->getLocalUserId(), 'trending_tags')) {
160 $this->page['aside'] .= TrendingTags::getHTML($this->selectedTab);
163 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll') && ($_GET['mode'] ?? '') != 'minimal') {
164 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
165 $o .= Renderer::replaceMacros($tpl, ['$reload_uri' => $this->args->getQueryString()]);
168 if (!(isset($_GET['mode']) and ($_GET['mode'] == 'raw'))) {
169 $o .= $this->getTabsHTML();
171 Nav::setSelected($this->args->get(0));
175 if ($this->groupContactId) {
176 // If $this->groupContactId belongs to a community group or a private group, add a mention to the status editor
177 $condition = ["`id` = ? AND `contact-type` = ?", $this->groupContactId, Contact::TYPE_COMMUNITY];
178 $contact = $this->database->selectFirst('contact', ['addr'], $condition);
179 if (!empty($contact['addr'])) {
180 $content = '!' . $contact['addr'];
184 $default_permissions = [];
185 if ($this->circleId) {
186 $default_permissions['allow_gid'] = [$this->circleId];
190 if ($this->groupContactId) {
191 $allowedCids[] = (int) $this->groupContactId;
192 } elseif ($this->network) {
194 'uid' => $this->session->getLocalUserId(),
195 'network' => $this->network,
200 'rel' => [Contact::SHARING, Contact::FRIEND],
202 $contactStmt = $this->database->select('contact', ['id'], $condition);
203 while ($contact = $this->database->fetch($contactStmt)) {
204 $allowedCids[] = (int) $contact['id'];
206 $this->database->close($contactStmt);
209 if (count($allowedCids)) {
210 $default_permissions['allow_cid'] = $allowedCids;
214 'lockstate' => $this->circleId || $this->groupContactId || $this->network || ACL::getLockstateForUserId($this->session->getLocalUserId()) ? 'lock' : 'unlock',
215 'acl' => ACL::getFullSelectorHTML($this->page, $this->session->getLocalUserId(), true, $default_permissions),
216 'bang' => (($this->circleId || $this->groupContactId || $this->network) ? '!' : ''),
217 'content' => $content,
220 $o .= $this->conversation->statusEditor($x);
223 if ($this->circleId) {
224 $circle = $this->database->selectFirst('group', ['name'], ['id' => $this->circleId, 'uid' => $this->session->getLocalUserId()]);
225 if (!$this->database->isResult($circle)) {
226 $this->systemMessages->addNotice($this->l10n->t('No such circle'));
229 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
230 '$title' => $this->l10n->t('Circle: %s', $circle['name'])
232 } elseif ($this->groupContactId) {
233 $contact = Contact::getById($this->groupContactId);
234 if ($this->database->isResult($contact)) {
235 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('contact/list.tpl'), [
236 'contacts' => [ModuleContact::getContactTemplateVars($contact)],
237 'id' => $this->args->get(0),
240 $this->systemMessages->addNotice($this->l10n->t('Invalid contact.'));
242 } elseif (!$this->config->get('theme', 'hide_eventlist')) {
243 $o .= Profile::getBirthdays();
244 $o .= Profile::getEventsReminderHTML();
247 $o .= $this->conversation->render($items, Conversation::MODE_NETWORK, false, false, $this->getOrder(), $this->session->getLocalUserId());
249 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
250 $o .= HTML::scrollLoader();
252 $pager = new BoundariesPager(
254 $this->args->getQueryString(),
255 $items[0][$this->order] ?? null,
256 $items[count($items) - 1][$this->order] ?? null,
260 $o .= $pager->renderMinimal(count($items));
266 protected function getOrder(): string
268 if ($this->order === 'received') {
270 } elseif ($this->order === 'created') {
273 return '`commented`';
278 * Get the network tabs menu
280 * @return string Html of the network tabs
281 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
283 private function getTabsHTML()
285 $tabs = $this->getTabArray($this->networkFactory->getTimelines($this->args->getCommand()), 'network');
287 $network_timelines = $this->pConfig->get($this->session->getLocalUserId(), 'system', 'network_timelines', []);
288 if (!empty($network_timelines)) {
289 $tabs = array_merge($tabs, $this->getTabArray($this->channelFactory->getTimelines($this->session->getLocalUserId()), 'network', 'channel'));
290 $tabs = array_merge($tabs, $this->getTabArray($this->userDefinedChannel->getForUser($this->session->getLocalUserId()), 'network', 'channel'));
291 $tabs = array_merge($tabs, $this->getTabArray($this->community->getTimelines(true), 'network', 'channel'));
294 $arr = ['tabs' => $tabs];
295 Hook::callAll('network_tabs', $arr);
297 if (!empty($network_timelines)) {
300 foreach ($arr['tabs'] as $tab) {
301 if (in_array($tab['code'], $network_timelines)) {
306 $tabs = $arr['tabs'];
309 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
311 return Renderer::replaceMacros($tpl, ['$tabs' => $tabs]);
314 protected function parseRequest(array $request)
316 parent::parseRequest($request);
318 $this->circleId = (int)($this->parameters['circle_id'] ?? 0);
320 $this->groupContactId = (int)($this->parameters['contact_id'] ?? 0);
322 if (!$this->selectedTab) {
323 $this->selectedTab = self::getTimelineOrderBySession($this->session, $this->pConfig);
324 } elseif (!$this->networkFactory->isTimeline($this->selectedTab) && !$this->channelFactory->isTimeline($this->selectedTab) && !$this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId()) && !$this->community->isTimeline($this->selectedTab)) {
325 throw new HTTPException\BadRequestException($this->l10n->t('Network feed not available.'));
328 if (($this->network || $this->circleId || $this->groupContactId) && ($this->channelFactory->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId()) || $this->community->isTimeline($this->selectedTab))) {
329 $this->selectedTab = NetworkEntity::RECEIVED;
332 if (!empty($request['star'])) {
333 $this->selectedTab = NetworkEntity::STAR;
336 $this->star = $this->selectedTab == NetworkEntity::STAR;
339 if (!empty($request['mention'])) {
340 $this->selectedTab = NetworkEntity::MENTION;
341 $this->mention = true;
343 $this->mention = $this->selectedTab == NetworkEntity::MENTION;
346 if (!empty($request['order'])) {
347 $this->selectedTab = $request['order'];
348 $this->order = $request['order'];
350 $this->mention = false;
351 } elseif (in_array($this->selectedTab, [NetworkEntity::RECEIVED, NetworkEntity::STAR]) || $this->community->isTimeline($this->selectedTab)) {
352 $this->order = 'received';
353 } elseif (($this->selectedTab == NetworkEntity::CREATED) || $this->channelFactory->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId())) {
354 $this->order = 'created';
356 $this->order = 'commented';
359 $this->selectedTab = $this->selectedTab ?? $this->order;
361 // Upon updates in the background and order by last comment we order by received date,
362 // since otherwise the feed will optically jump, when some already visible thread has been updated.
363 if ($this->update && ($this->selectedTab == NetworkEntity::COMMENTED)) {
364 $this->order = 'received';
365 $request['last_received'] = $request['last_commented'] ?? null;
366 $request['first_received'] = $request['first_commented'] ?? null;
369 // Prohibit combined usage of "star" and "mention"
370 if ($this->selectedTab == NetworkEntity::STAR) {
371 $this->mention = false;
372 } elseif ($this->selectedTab == NetworkEntity::MENTION) {
376 $this->session->set('network-tab', $this->selectedTab);
377 $this->pConfig->set($this->session->getLocalUserId(), 'network.view', 'selected_tab', $this->selectedTab);
379 $this->network = $request['nets'] ?? '';
381 $this->dateFrom = $this->parameters['from'] ?? '';
382 $this->dateTo = $this->parameters['to'] ?? '';
384 switch ($this->order) {
386 $this->maxId = $request['last_received'] ?? $this->maxId;
387 $this->minId = $request['first_received'] ?? $this->minId;
390 $this->maxId = $request['last_created'] ?? $this->maxId;
391 $this->minId = $request['first_created'] ?? $this->minId;
394 $this->maxId = $request['last_uriid'] ?? $this->maxId;
395 $this->minId = $request['first_uriid'] ?? $this->minId;
398 $this->order = 'commented';
399 $this->maxId = $request['last_commented'] ?? $this->maxId;
400 $this->minId = $request['first_commented'] ?? $this->minId;
404 protected function getItems()
406 $conditionFields = ['uid' => $this->session->getLocalUserId()];
407 $conditionStrings = [];
409 if (!is_null($this->accountType)) {
410 $conditionFields['contact-type'] = $this->accountType;
414 $conditionFields['starred'] = true;
416 if ($this->mention) {
417 $conditionFields['mention'] = true;
419 if ($this->network) {
420 $conditionFields['network'] = $this->network;
423 if ($this->dateFrom) {
424 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` <= ? ", DateTimeFormat::convert($this->dateFrom, 'UTC', $this->app->getTimeZone())]);
427 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` >= ? ", DateTimeFormat::convert($this->dateTo, 'UTC', $this->app->getTimeZone())]);
430 if ($this->circleId) {
431 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`contact-id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)", $this->circleId]);
432 } elseif ($this->groupContactId) {
433 $conditionStrings = DBA::mergeConditions($conditionStrings,
434 ["((`contact-id` = ?) OR `uri-id` IN (SELECT `parent-uri-id` FROM `post-user-view` WHERE (`contact-id` = ? AND `gravity` = ? AND `vid` = ? AND `uid` = ?)))",
435 $this->groupContactId, $this->groupContactId, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), $this->session->getLocalUserId()]);
438 // Currently only the order modes "received" and "commented" are in use
439 if (!empty($this->itemUriId)) {
440 $conditionStrings = DBA::mergeConditions($conditionStrings, ['uri-id' => $this->itemUriId]);
442 if (isset($this->maxId)) {
443 switch ($this->order) {
445 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` < ?", $this->maxId]);
448 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` < ?", $this->maxId]);
451 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` < ?", $this->maxId]);
454 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` < ?", $this->maxId]);
459 if (isset($this->minId)) {
460 switch ($this->order) {
462 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` > ?", $this->minId]);
465 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` > ?", $this->minId]);
468 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` > ?", $this->minId]);
471 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` > ?", $this->minId]);
477 $params = ['limit' => $this->itemsPerPage];
479 if (isset($this->minId) && !isset($this->maxId)) {
480 // min_id quirk: querying in reverse order with min_id gets the most recent rows, regardless of how close
481 // they are to min_id. We change the query ordering to get the expected data, and we need to reverse the
482 // order of the results.
483 $params['order'] = [$this->order => false];
485 $params['order'] = [$this->order => true];
488 $items = $this->database->selectToArray('network-thread-view', [], DBA::mergeConditions($conditionFields, $conditionStrings), $params);
490 // min_id quirk, continued
491 if (isset($this->minId) && !isset($this->maxId)) {
492 $items = array_reverse($items);
495 if ($this->database->isResult($items)) {
496 $parents = array_column($items, 'uri-id');
501 // We aren't going to try and figure out at the item, circle, and page
502 // level which items you've seen and which you haven't. If you're looking
503 // at the top level network page just mark everything seen.
504 if (!$this->circleId && !$this->groupContactId && !$this->star && !$this->mention) {
505 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId()];
506 $this->setItemsSeenByCondition($condition);
507 } elseif (!empty($parents)) {
508 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => $parents];
509 $this->setItemsSeenByCondition($condition);
516 * Returns the selected network tab of the currently logged-in user
518 * @param IHandleUserSessions $session
519 * @param IManagePersonalConfigValues $pconfig
522 public static function getTimelineOrderBySession(IHandleUserSessions $session, IManagePersonalConfigValues $pconfig): string
524 return $session->get('network-tab')
525 ?? $pconfig->get($session->getLocalUserId(), 'network.view', 'selected_tab')