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
64 private static $circleId;
66 private static $groupContactId;
68 private static $network;
70 private static $dateFrom;
72 private static $dateTo;
76 private static $mention;
78 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(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', self::$circleId);
149 $this->page['aside'] .= GroupManager::widget($module . '/group', $this->session->getLocalUserId(), self::$groupContactId);
150 $this->page['aside'] .= Widget::postedByYear($module . '/archive', $this->session->getLocalUserId(), false);
151 $this->page['aside'] .= Widget::networks($module, !self::$groupContactId ? self::$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 (self::$groupContactId) {
171 // If self::$groupContactId belongs to a community group or a private group, add a mention to the status editor
172 $condition = ["`id` = ? AND `contact-type` = ?", self::$groupContactId, Contact::TYPE_COMMUNITY];
173 $contact = DBA::selectFirst('contact', ['addr'], $condition);
174 if (!empty($contact['addr'])) {
175 $content = '!' . $contact['addr'];
179 $default_permissions = [];
180 if (self::$circleId) {
181 $default_permissions['allow_gid'] = [self::$circleId];
185 if (self::$groupContactId) {
186 $allowedCids[] = (int) self::$groupContactId;
187 } elseif (self::$network) {
189 'uid' => $this->session->getLocalUserId(),
190 'network' => self::$network,
195 'rel' => [Contact::SHARING, Contact::FRIEND],
197 $contactStmt = DBA::select('contact', ['id'], $condition);
198 while ($contact = DBA::fetch($contactStmt)) {
199 $allowedCids[] = (int) $contact['id'];
201 DBA::close($contactStmt);
204 if (count($allowedCids)) {
205 $default_permissions['allow_cid'] = $allowedCids;
209 'lockstate' => self::$circleId || self::$groupContactId || self::$network || ACL::getLockstateForUserId($this->session->getLocalUserId()) ? 'lock' : 'unlock',
210 'acl' => ACL::getFullSelectorHTML($this->page, $this->session->getLocalUserId(), true, $default_permissions),
211 'bang' => ((self::$circleId || self::$groupContactId || self::$network) ? '!' : ''),
212 'content' => $content,
215 $o .= $this->conversation->statusEditor($x);
218 if (self::$circleId) {
219 $circle = DBA::selectFirst('group', ['name'], ['id' => self::$circleId, 'uid' => $this->session->getLocalUserId()]);
220 if (!DBA::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 (self::$groupContactId) {
228 $contact = Contact::getById(self::$groupContactId);
229 if (DBA::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][self::$order] ?? null,
251 $items[count($items) - 1][self::$order] ?? null,
255 $o .= $pager->renderMinimal(count($items));
261 protected function getOrder(): string
263 if (self::$order === 'received') {
265 } elseif (self::$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 $arr = ['tabs' => $tabs];
284 Hook::callAll('network_tabs', $arr);
286 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
288 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
291 protected function parseRequest(array $request)
293 parent::parseRequest($request);
295 self::$circleId = (int)($this->parameters['circle_id'] ?? 0);
297 self::$groupContactId = (int)($this->parameters['contact_id'] ?? 0);
299 if (!$this->selectedTab) {
300 $this->selectedTab = self::getTimelineOrderBySession($this->session, $this->pConfig);
301 } elseif (!$this->timeline->isChannel($this->selectedTab) && !$this->timeline->isCommunity($this->selectedTab)) {
302 throw new HTTPException\BadRequestException($this->l10n->t('Network feed not available.'));
306 if (!empty($request['star'])) {
307 $this->selectedTab = TimelineEntity::STAR;
310 self::$star = $this->selectedTab == TimelineEntity::STAR;
313 if (!empty($request['mention'])) {
314 $this->selectedTab = TimelineEntity::MENTION;
315 self::$mention = true;
317 self::$mention = $this->selectedTab == TimelineEntity::MENTION;
320 if (!empty($request['order'])) {
321 $this->selectedTab = $request['order'];
322 self::$order = $request['order'];
324 self::$mention = false;
325 } elseif (in_array($this->selectedTab, [TimelineEntity::RECEIVED, TimelineEntity::STAR])) {
326 self::$order = 'received';
327 } elseif (($this->selectedTab == TimelineEntity::CREATED) || $this->timeline->isChannel($this->selectedTab)) {
328 self::$order = 'created';
330 self::$order = 'commented';
333 $this->selectedTab = $this->selectedTab ?? self::$order;
335 // Prohibit combined usage of "star" and "mention"
336 if ($this->selectedTab == TimelineEntity::STAR) {
337 self::$mention = false;
338 } elseif ($this->selectedTab == TimelineEntity::MENTION) {
342 $this->session->set('network-tab', $this->selectedTab);
343 $this->pConfig->set($this->session->getLocalUserId(), 'network.view', 'selected_tab', $this->selectedTab);
345 self::$network = $request['nets'] ?? '';
347 self::$dateFrom = $this->parameters['from'] ?? '';
348 self::$dateTo = $this->parameters['to'] ?? '';
350 switch (self::$order) {
352 $this->maxId = $request['last_received'] ?? $this->maxId;
355 $this->maxId = $request['last_created'] ?? $this->maxId;
358 $this->maxId = $request['last_uriid'] ?? $this->maxId;
361 self::$order = 'commented';
362 $this->maxId = $request['last_commented'] ?? $this->maxId;
366 protected function getItems()
368 $conditionFields = ['uid' => $this->session->getLocalUserId()];
369 $conditionStrings = [];
371 if (!is_null($this->accountType)) {
372 $conditionFields['contact-type'] = $this->accountType;
376 $conditionFields['starred'] = true;
378 if (self::$mention) {
379 $conditionFields['mention'] = true;
381 if (self::$network) {
382 $conditionFields['network'] = self::$network;
385 if (self::$dateFrom) {
386 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` <= ? ", DateTimeFormat::convert(self::$dateFrom, 'UTC', $this->app->getTimeZone())]);
389 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` >= ? ", DateTimeFormat::convert(self::$dateTo, 'UTC', $this->app->getTimeZone())]);
392 if (self::$circleId) {
393 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`contact-id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)", self::$circleId]);
394 } elseif (self::$groupContactId) {
395 $conditionStrings = DBA::mergeConditions($conditionStrings,
396 ["((`contact-id` = ?) OR `uri-id` IN (SELECT `parent-uri-id` FROM `post-user-view` WHERE (`contact-id` = ? AND `gravity` = ? AND `vid` = ? AND `uid` = ?)))",
397 self::$groupContactId, self::$groupContactId, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), $this->session->getLocalUserId()]);
400 // Currently only the order modes "received" and "commented" are in use
401 if (!empty($this->itemUriId)) {
402 $conditionStrings = DBA::mergeConditions($conditionStrings, ['uri-id' => $this->itemUriId]);
404 if (isset($this->maxId)) {
405 switch (self::$order) {
407 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` < ?", $this->maxId]);
410 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` < ?", $this->maxId]);
413 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` < ?", $this->maxId]);
416 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` < ?", $this->maxId]);
421 if (isset($this->minId)) {
422 switch (self::$order) {
424 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` > ?", $this->minId]);
427 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` > ?", $this->minId]);
430 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` > ?", $this->minId]);
433 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` > ?", $this->minId]);
439 $params = ['limit' => $this->itemsPerPage];
441 if (isset($this->minId) && !isset($this->maxId)) {
442 // min_id quirk: querying in reverse order with min_id gets the most recent rows, regardless of how close
443 // they are to min_id. We change the query ordering to get the expected data, and we need to reverse the
444 // order of the results.
445 $params['order'] = [self::$order => false];
447 $params['order'] = [self::$order => true];
450 $items = DBA::selectToArray('network-thread-view', [], DBA::mergeConditions($conditionFields, $conditionStrings), $params);
452 // min_id quirk, continued
453 if (isset($this->minId) && !isset($this->maxId)) {
454 $items = array_reverse($items);
457 if (DBA::isResult($items)) {
458 $parents = array_column($items, 'uri-id');
463 // We aren't going to try and figure out at the item, circle, and page
464 // level which items you've seen and which you haven't. If you're looking
465 // at the top level network page just mark everything seen.
466 if (!self::$circleId && !self::$groupContactId && !self::$star && !self::$mention) {
467 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId()];
468 $this->setItemsSeenByCondition($condition);
469 } elseif (!empty($parents)) {
470 $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => $parents];
471 $this->setItemsSeenByCondition($condition);
478 * Returns the selected network tab of the currently logged-in user
480 * @param IHandleUserSessions $session
481 * @param IManagePersonalConfigValues $pconfig
484 public static function getTimelineOrderBySession(IHandleUserSessions $session, IManagePersonalConfigValues $pconfig): string
486 return $session->get('network-tab')
487 ?? $pconfig->get($session->getLocalUserId(), 'network.view', 'selected_tab')