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, self::$accountTypeString);
121 $arr = ['query' => $this->args->getQueryString()];
122 Hook::callAll('network_content_init', $arr);
126 if ($this->timeline->isChannel(self::$selectedTab)) {
127 if (!in_array(self::$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(self::$selectedTab);
135 $items = $this->getChannelItems();
136 } elseif ($this->timeline->isCommunity(self::$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(self::$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 // Fetch a page full of parent items for this page
155 $params = ['limit' => self::$itemsPerPage];
156 $table = 'network-thread-view';
158 $items = $this->getItems($table, $params);
161 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll') && ($_GET['mode'] ?? '') != 'minimal') {
162 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
163 $o .= Renderer::replaceMacros($tpl, ['$reload_uri' => $this->args->getQueryString()]);
166 if (!(isset($_GET['mode']) and ($_GET['mode'] == 'raw'))) {
167 $o .= $this->getTabsHTML();
169 Nav::setSelected($this->args->get(0));
173 if (self::$groupContactId) {
174 // If self::$groupContactId belongs to a community group or a private group, add a mention to the status editor
175 $condition = ["`id` = ? AND `contact-type` = ?", self::$groupContactId, Contact::TYPE_COMMUNITY];
176 $contact = DBA::selectFirst('contact', ['addr'], $condition);
177 if (!empty($contact['addr'])) {
178 $content = '!' . $contact['addr'];
182 $default_permissions = [];
183 if (self::$circleId) {
184 $default_permissions['allow_gid'] = [self::$circleId];
188 if (self::$groupContactId) {
189 $allowedCids[] = (int) self::$groupContactId;
190 } elseif (self::$network) {
192 'uid' => $this->session->getLocalUserId(),
193 'network' => self::$network,
198 'rel' => [Contact::SHARING, Contact::FRIEND],
200 $contactStmt = DBA::select('contact', ['id'], $condition);
201 while ($contact = DBA::fetch($contactStmt)) {
202 $allowedCids[] = (int) $contact['id'];
204 DBA::close($contactStmt);
207 if (count($allowedCids)) {
208 $default_permissions['allow_cid'] = $allowedCids;
212 'lockstate' => self::$circleId || self::$groupContactId || self::$network || ACL::getLockstateForUserId($this->session->getLocalUserId()) ? 'lock' : 'unlock',
213 'acl' => ACL::getFullSelectorHTML($this->page, $this->session->getLocalUserId(), true, $default_permissions),
214 'bang' => ((self::$circleId || self::$groupContactId || self::$network) ? '!' : ''),
215 'content' => $content,
218 $o .= $this->conversation->statusEditor($x);
221 if (self::$circleId) {
222 $circle = DBA::selectFirst('group', ['name'], ['id' => self::$circleId, 'uid' => $this->session->getLocalUserId()]);
223 if (!DBA::isResult($circle)) {
224 $this->systemMessages->addNotice($this->l10n->t('No such circle'));
227 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
228 '$title' => $this->l10n->t('Circle: %s', $circle['name'])
230 } elseif (self::$groupContactId) {
231 $contact = Contact::getById(self::$groupContactId);
232 if (DBA::isResult($contact)) {
233 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('contact/list.tpl'), [
234 'contacts' => [ModuleContact::getContactTemplateVars($contact)],
235 'id' => $this->args->get(0),
238 $this->systemMessages->addNotice($this->l10n->t('Invalid contact.'));
240 } elseif (!$this->config->get('theme', 'hide_eventlist')) {
241 $o .= Profile::getBirthdays();
242 $o .= Profile::getEventsReminderHTML();
245 if (self::$order === 'received') {
246 $ordering = '`received`';
247 } elseif (self::$order === 'created') {
248 $ordering = '`created`';
250 $ordering = '`commented`';
253 $o .= $this->conversation->render($items, Conversation::MODE_NETWORK, false, false, $ordering, $this->session->getLocalUserId());
255 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
256 $o .= HTML::scrollLoader();
258 $pager = new BoundariesPager(
260 $this->args->getQueryString(),
261 $items[0][self::$order] ?? null,
262 $items[count($items) - 1][self::$order] ?? null,
266 $o .= $pager->renderMinimal(count($items));
275 * @param array $condition The array with the SQL condition
276 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
278 private static function setItemsSeenByCondition(array $condition)
280 if (empty($condition)) {
284 $unseen = Post::exists($condition);
287 /// @todo handle huge "unseen" updates in the background to avoid timeout errors
288 Item::update(['unseen' => false], $condition);
293 * Get the network tabs menu
295 * @return string Html of the network tabs
296 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
298 private function getTabsHTML()
300 // @todo user confgurable selection of tabs
301 $tabs = $this->getTabArray($this->timeline->getNetworkFeeds($this->args->getCommand()), 'network');
303 $arr = ['tabs' => $tabs];
304 Hook::callAll('network_tabs', $arr);
306 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
308 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
311 protected function parseRequest(array $request)
313 parent::parseRequest($request);
315 self::$circleId = (int)($this->parameters['circle_id'] ?? 0);
317 self::$groupContactId = (int)($this->parameters['contact_id'] ?? 0);
319 if (!self::$selectedTab) {
320 self::$selectedTab = self::getTimelineOrderBySession(DI::userSession(), $this->pConfig);
321 } elseif (!$this->timeline->isChannel(self::$selectedTab) && !$this->timeline->isCommunity(self::$selectedTab)) {
322 throw new HTTPException\BadRequestException($this->l10n->t('Network feed not available.'));
326 if (!empty($request['star'])) {
327 self::$selectedTab = TimelineEntity::STAR;
330 self::$star = self::$selectedTab == TimelineEntity::STAR;
333 if (!empty($request['mention'])) {
334 self::$selectedTab = TimelineEntity::MENTION;
335 self::$mention = true;
337 self::$mention = self::$selectedTab == TimelineEntity::MENTION;
340 if (!empty($request['order'])) {
341 self::$selectedTab = $request['order'];
342 self::$order = $request['order'];
344 self::$mention = false;
345 } elseif (in_array(self::$selectedTab, [TimelineEntity::RECEIVED, TimelineEntity::STAR])) {
346 self::$order = 'received';
347 } elseif ((self::$selectedTab == TimelineEntity::CREATED) || $this->timeline->isChannel(self::$selectedTab)) {
348 self::$order = 'created';
350 self::$order = 'commented';
353 self::$selectedTab = self::$selectedTab ?? self::$order;
355 // Prohibit combined usage of "star" and "mention"
356 if (self::$selectedTab == TimelineEntity::STAR) {
357 self::$mention = false;
358 } elseif (self::$selectedTab == TimelineEntity::MENTION) {
362 $this->session->set('network-tab', self::$selectedTab);
363 $this->pConfig->set($this->session->getLocalUserId(), 'network.view', 'selected_tab', self::$selectedTab);
365 self::$network = $request['nets'] ?? '';
367 self::$dateFrom = $this->parameters['from'] ?? '';
368 self::$dateTo = $this->parameters['to'] ?? '';
370 switch (self::$order) {
372 self::$max_id = $request['last_received'] ?? self::$max_id;
375 self::$max_id = $request['last_created'] ?? self::$max_id;
378 self::$max_id = $request['last_uriid'] ?? self::$max_id;
381 self::$order = 'commented';
382 self::$max_id = $request['last_commented'] ?? self::$max_id;
386 protected function getItems(string $table, array $params, array $conditionFields = [])
388 $conditionFields['uid'] = $this->session->getLocalUserId();
389 $conditionStrings = [];
391 if (!is_null(self::$accountType)) {
392 $conditionFields['contact-type'] = self::$accountType;
396 $conditionFields['starred'] = true;
398 if (self::$mention) {
399 $conditionFields['mention'] = true;
401 if (self::$network) {
402 $conditionFields['network'] = self::$network;
405 if (self::$dateFrom) {
406 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` <= ? ", DateTimeFormat::convert(self::$dateFrom, 'UTC', DI::app()->getTimeZone())]);
409 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` >= ? ", DateTimeFormat::convert(self::$dateTo, 'UTC', DI::app()->getTimeZone())]);
412 if (self::$circleId) {
413 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`contact-id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)", self::$circleId]);
414 } elseif (self::$groupContactId) {
415 $conditionStrings = DBA::mergeConditions($conditionStrings,
416 ["((`contact-id` = ?) OR `uri-id` IN (SELECT `parent-uri-id` FROM `post-user-view` WHERE (`contact-id` = ? AND `gravity` = ? AND `vid` = ? AND `uid` = ?)))",
417 self::$groupContactId, self::$groupContactId, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), $this->session->getLocalUserId()]);
420 // Currently only the order modes "received" and "commented" are in use
421 if (isset(self::$max_id)) {
422 switch (self::$order) {
424 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` < ?", self::$max_id]);
427 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` < ?", self::$max_id]);
430 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` < ?", self::$max_id]);
433 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` < ?", self::$max_id]);
438 if (isset(self::$min_id)) {
439 switch (self::$order) {
441 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` > ?", self::$min_id]);
444 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` > ?", self::$min_id]);
447 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` > ?", self::$min_id]);
450 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` > ?", self::$min_id]);
455 if (isset(self::$min_id) && !isset(self::$max_id)) {
456 // min_id quirk: querying in reverse order with min_id gets the most recent rows, regardless of how close
457 // they are to min_id. We change the query ordering to get the expected data, and we need to reverse the
458 // order of the results.
459 $params['order'] = [self::$order => false];
461 $params['order'] = [self::$order => true];
464 $items = DBA::selectToArray($table, [], DBA::mergeConditions($conditionFields, $conditionStrings), $params);
466 // min_id quirk, continued
467 if (isset(self::$min_id) && !isset(self::$max_id)) {
468 $items = array_reverse($items);
471 if (DBA::isResult($items)) {
472 $parents = array_column($items, 'uri-id');
477 // We aren't going to try and figure out at the item, circle, and page
478 // level which items you've seen and which you haven't. If you're looking
479 // at the top level network page just mark everything seen.
480 if (!self::$circleId && !self::$groupContactId && !self::$star && !self::$mention) {
481 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId()];
482 self::setItemsSeenByCondition($condition);
483 } elseif (!empty($parents)) {
484 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => $parents];
485 self::setItemsSeenByCondition($condition);
492 * Returns the selected network tab of the currently logged-in user
494 * @param IHandleUserSessions $session
495 * @param IManagePersonalConfigValues $pconfig
498 public static function getTimelineOrderBySession(IHandleUserSessions $session, IManagePersonalConfigValues $pconfig): string
500 return $session->get('network-tab')
501 ?? $pconfig->get($session->getLocalUserId(), 'network.view', 'selected_tab')