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;
47 use Friendica\Model\Contact;
48 use Friendica\Model\Circle;
49 use Friendica\Model\Item;
50 use Friendica\Model\Post;
51 use Friendica\Model\Profile;
52 use Friendica\Model\Verb;
53 use Friendica\Module\Contact as ModuleContact;
54 use Friendica\Module\Response;
55 use Friendica\Module\Security\Login;
56 use Friendica\Network\HTTPException;
57 use Friendica\Navigation\SystemMessages;
58 use Friendica\Util\DateTimeFormat;
59 use Friendica\Util\Profiler;
60 use Friendica\Protocol\Activity;
61 use Psr\Log\LoggerInterface;
63 class Network extends Timeline
66 private static $circleId;
68 private static $groupContactId;
70 private static $network;
72 private static $dateFrom;
74 private static $dateTo;
78 private static $mention;
80 protected static $order;
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(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);
103 $this->timeline = $timeline;
104 $this->systemMessages = $systemMessages;
105 $this->conversation = $conversation;
109 protected function content(array $request = []): string
111 if (!$this->session->getLocalUserId()) {
112 return Login::form();
115 $this->parseRequest($request);
119 $this->page['aside'] .= Widget::accountTypes($module, $this->accountTypeString);
121 $arr = ['query' => $this->args->getQueryString()];
122 Hook::callAll('network_content_init', $arr);
126 if ($this->timeline->isChannel($this->selectedTab)) {
127 if (!in_array($this->selectedTab, [TimelineEntity::FOLLOWERS, TimelineEntity::FORYOU]) && $this->config->get('system', 'community_no_sharer')) {
128 $this->page['aside'] .= $this->getNoSharerWidget($module);
131 if (Feature::isEnabled($this->session->getLocalUserId(), 'trending_tags')) {
132 $this->page['aside'] .= TrendingTags::getHTML($this->selectedTab);
135 $items = $this->getChannelItems();
136 } elseif ($this->timeline->isCommunity($this->selectedTab)) {
137 if ($this->session->getLocalUserId() && $this->config->get('system', 'community_no_sharer')) {
138 $this->page['aside'] .= $this->getNoSharerWidget($module);
141 if (Feature::isEnabled($this->session->getLocalUserId(), 'trending_tags')) {
142 $this->page['aside'] .= TrendingTags::getHTML($this->selectedTab);
145 $items = $this->getCommunityItems();
147 $this->page['aside'] .= Circle::sidebarWidget($module, $module . '/circle', 'standard', self::$circleId);
148 $this->page['aside'] .= GroupManager::widget($module . '/group', $this->session->getLocalUserId(), self::$groupContactId);
149 $this->page['aside'] .= Widget::postedByYear($module . '/archive', $this->session->getLocalUserId(), false);
150 $this->page['aside'] .= Widget::networks($module, !self::$groupContactId ? self::$network : '');
151 $this->page['aside'] .= Widget\SavedSearches::getHTML($this->args->getQueryString());
152 $this->page['aside'] .= Widget::fileAs('filed', '');
154 $items = $this->getItems();
157 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll') && ($_GET['mode'] ?? '') != 'minimal') {
158 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
159 $o .= Renderer::replaceMacros($tpl, ['$reload_uri' => $this->args->getQueryString()]);
162 if (!(isset($_GET['mode']) and ($_GET['mode'] == 'raw'))) {
163 $o .= $this->getTabsHTML();
165 Nav::setSelected($this->args->get(0));
169 if (self::$groupContactId) {
170 // If self::$groupContactId belongs to a community group or a private group, add a mention to the status editor
171 $condition = ["`id` = ? AND `contact-type` = ?", self::$groupContactId, Contact::TYPE_COMMUNITY];
172 $contact = DBA::selectFirst('contact', ['addr'], $condition);
173 if (!empty($contact['addr'])) {
174 $content = '!' . $contact['addr'];
178 $default_permissions = [];
179 if (self::$circleId) {
180 $default_permissions['allow_gid'] = [self::$circleId];
184 if (self::$groupContactId) {
185 $allowedCids[] = (int) self::$groupContactId;
186 } elseif (self::$network) {
188 'uid' => $this->session->getLocalUserId(),
189 'network' => self::$network,
194 'rel' => [Contact::SHARING, Contact::FRIEND],
196 $contactStmt = DBA::select('contact', ['id'], $condition);
197 while ($contact = DBA::fetch($contactStmt)) {
198 $allowedCids[] = (int) $contact['id'];
200 DBA::close($contactStmt);
203 if (count($allowedCids)) {
204 $default_permissions['allow_cid'] = $allowedCids;
208 'lockstate' => self::$circleId || self::$groupContactId || self::$network || ACL::getLockstateForUserId($this->session->getLocalUserId()) ? 'lock' : 'unlock',
209 'acl' => ACL::getFullSelectorHTML($this->page, $this->session->getLocalUserId(), true, $default_permissions),
210 'bang' => ((self::$circleId || self::$groupContactId || self::$network) ? '!' : ''),
211 'content' => $content,
214 $o .= $this->conversation->statusEditor($x);
217 if (self::$circleId) {
218 $circle = DBA::selectFirst('group', ['name'], ['id' => self::$circleId, 'uid' => $this->session->getLocalUserId()]);
219 if (!DBA::isResult($circle)) {
220 $this->systemMessages->addNotice($this->l10n->t('No such circle'));
223 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
224 '$title' => $this->l10n->t('Circle: %s', $circle['name'])
226 } elseif (self::$groupContactId) {
227 $contact = Contact::getById(self::$groupContactId);
228 if (DBA::isResult($contact)) {
229 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('contact/list.tpl'), [
230 'contacts' => [ModuleContact::getContactTemplateVars($contact)],
231 'id' => $this->args->get(0),
234 $this->systemMessages->addNotice($this->l10n->t('Invalid contact.'));
236 } elseif (!$this->config->get('theme', 'hide_eventlist')) {
237 $o .= Profile::getBirthdays();
238 $o .= Profile::getEventsReminderHTML();
241 $o .= $this->conversation->render($items, Conversation::MODE_NETWORK, false, false, $this->getOrder(), $this->session->getLocalUserId());
243 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
244 $o .= HTML::scrollLoader();
246 $pager = new BoundariesPager(
248 $this->args->getQueryString(),
249 $items[0][self::$order] ?? null,
250 $items[count($items) - 1][self::$order] ?? null,
254 $o .= $pager->renderMinimal(count($items));
260 protected function getOrder(): string
262 if (self::$order === 'received') {
264 } elseif (self::$order === 'created') {
267 return '`commented`';
274 * @param array $condition The array with the SQL condition
275 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
277 private static function setItemsSeenByCondition(array $condition)
279 if (empty($condition)) {
283 $unseen = Post::exists($condition);
286 /// @todo handle huge "unseen" updates in the background to avoid timeout errors
287 Item::update(['unseen' => false], $condition);
292 * Get the network tabs menu
294 * @return string Html of the network tabs
295 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
297 private function getTabsHTML()
299 // @todo user confgurable selection of tabs
300 $tabs = $this->getTabArray($this->timeline->getNetworkFeeds($this->args->getCommand()), 'network');
302 $arr = ['tabs' => $tabs];
303 Hook::callAll('network_tabs', $arr);
305 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
307 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
310 protected function parseRequest(array $request)
312 parent::parseRequest($request);
314 self::$circleId = (int)($this->parameters['circle_id'] ?? 0);
316 self::$groupContactId = (int)($this->parameters['contact_id'] ?? 0);
318 if (!$this->selectedTab) {
319 $this->selectedTab = self::getTimelineOrderBySession(DI::userSession(), $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.'));
325 if (!empty($request['star'])) {
326 $this->selectedTab = TimelineEntity::STAR;
329 self::$star = $this->selectedTab == TimelineEntity::STAR;
332 if (!empty($request['mention'])) {
333 $this->selectedTab = TimelineEntity::MENTION;
334 self::$mention = true;
336 self::$mention = $this->selectedTab == TimelineEntity::MENTION;
339 if (!empty($request['order'])) {
340 $this->selectedTab = $request['order'];
341 self::$order = $request['order'];
343 self::$mention = false;
344 } elseif (in_array($this->selectedTab, [TimelineEntity::RECEIVED, TimelineEntity::STAR])) {
345 self::$order = 'received';
346 } elseif (($this->selectedTab == TimelineEntity::CREATED) || $this->timeline->isChannel($this->selectedTab)) {
347 self::$order = 'created';
349 self::$order = 'commented';
352 $this->selectedTab = $this->selectedTab ?? self::$order;
354 // Prohibit combined usage of "star" and "mention"
355 if ($this->selectedTab == TimelineEntity::STAR) {
356 self::$mention = false;
357 } elseif ($this->selectedTab == TimelineEntity::MENTION) {
361 $this->session->set('network-tab', $this->selectedTab);
362 $this->pConfig->set($this->session->getLocalUserId(), 'network.view', 'selected_tab', $this->selectedTab);
364 self::$network = $request['nets'] ?? '';
366 self::$dateFrom = $this->parameters['from'] ?? '';
367 self::$dateTo = $this->parameters['to'] ?? '';
369 switch (self::$order) {
371 $this->maxId = $request['last_received'] ?? $this->maxId;
374 $this->maxId = $request['last_created'] ?? $this->maxId;
377 $this->maxId = $request['last_uriid'] ?? $this->maxId;
380 self::$order = 'commented';
381 $this->maxId = $request['last_commented'] ?? $this->maxId;
385 protected function getItems()
387 $conditionFields = ['uid' => $this->session->getLocalUserId()];
388 $conditionStrings = [];
390 if (!is_null($this->accountType)) {
391 $conditionFields['contact-type'] = $this->accountType;
395 $conditionFields['starred'] = true;
397 if (self::$mention) {
398 $conditionFields['mention'] = true;
400 if (self::$network) {
401 $conditionFields['network'] = self::$network;
404 if (self::$dateFrom) {
405 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` <= ? ", DateTimeFormat::convert(self::$dateFrom, 'UTC', DI::app()->getTimeZone())]);
408 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` >= ? ", DateTimeFormat::convert(self::$dateTo, 'UTC', DI::app()->getTimeZone())]);
411 if (self::$circleId) {
412 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`contact-id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)", self::$circleId]);
413 } elseif (self::$groupContactId) {
414 $conditionStrings = DBA::mergeConditions($conditionStrings,
415 ["((`contact-id` = ?) OR `uri-id` IN (SELECT `parent-uri-id` FROM `post-user-view` WHERE (`contact-id` = ? AND `gravity` = ? AND `vid` = ? AND `uid` = ?)))",
416 self::$groupContactId, self::$groupContactId, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), $this->session->getLocalUserId()]);
419 // Currently only the order modes "received" and "commented" are in use
420 if (!empty($this->itemUriId)) {
421 $conditionStrings = DBA::mergeConditions($conditionStrings, ['uri-id' => $this->itemUriId]);
423 if (isset($this->maxId)) {
424 switch (self::$order) {
426 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` < ?", $this->maxId]);
429 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` < ?", $this->maxId]);
432 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` < ?", $this->maxId]);
435 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` < ?", $this->maxId]);
440 if (isset($this->minId)) {
441 switch (self::$order) {
443 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` > ?", $this->minId]);
446 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` > ?", $this->minId]);
449 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` > ?", $this->minId]);
452 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` > ?", $this->minId]);
458 $params = ['limit' => $this->itemsPerPage];
460 if (isset($this->minId) && !isset($this->maxId)) {
461 // min_id quirk: querying in reverse order with min_id gets the most recent rows, regardless of how close
462 // they are to min_id. We change the query ordering to get the expected data, and we need to reverse the
463 // order of the results.
464 $params['order'] = [self::$order => false];
466 $params['order'] = [self::$order => true];
469 $items = DBA::selectToArray('network-thread-view', [], DBA::mergeConditions($conditionFields, $conditionStrings), $params);
471 // min_id quirk, continued
472 if (isset($this->minId) && !isset($this->maxId)) {
473 $items = array_reverse($items);
476 if (DBA::isResult($items)) {
477 $parents = array_column($items, 'uri-id');
482 // We aren't going to try and figure out at the item, circle, and page
483 // level which items you've seen and which you haven't. If you're looking
484 // at the top level network page just mark everything seen.
485 if (!self::$circleId && !self::$groupContactId && !self::$star && !self::$mention) {
486 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId()];
487 self::setItemsSeenByCondition($condition);
488 } elseif (!empty($parents)) {
489 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => $parents];
490 self::setItemsSeenByCondition($condition);
497 * Returns the selected network tab of the currently logged-in user
499 * @param IHandleUserSessions $session
500 * @param IManagePersonalConfigValues $pconfig
503 public static function getTimelineOrderBySession(IHandleUserSessions $session, IManagePersonalConfigValues $pconfig): string
505 return $session->get('network-tab')
506 ?? $pconfig->get($session->getLocalUserId(), 'network.view', 'selected_tab')