]> git.mxchange.org Git - friendica.git/blob - src/Module/Conversation/Network.php
Improved timeline menu
[friendica.git] / src / Module / Conversation / Network.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Module\Conversation;
23
24 use Friendica\App;
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;
61
62 class Network extends Timeline
63 {
64         /** @var int */
65         protected $circleId;
66         /** @var int */
67         protected $groupContactId;
68         /** @var string */
69         protected $network;
70         /** @var string */
71         protected $dateFrom;
72         /** @var string */
73         protected $dateTo;
74         /** @var int */
75         protected $star;
76         /** @var int */
77         protected $mention;
78         /** @var string */
79         protected $order;
80
81         /** @var App */
82         protected $app;
83         /** @var ICanCache */
84         protected $cache;
85         /** @var IManageConfigValues The config */
86         protected $config;
87         /** @var SystemMessages */
88         protected $systemMessages;
89         /** @var App\Page */
90         protected $page;
91         /** @var Conversation */
92         protected $conversation;
93         /** @var IManagePersonalConfigValues */
94         protected $pConfig;
95         /** @var Database */
96         protected $database;
97         /** @var TimelineFactory */
98         protected $timeline;
99
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 = [])
101         {
102                 parent::__construct($channel, $mode, $session, $database, $pConfig, $config, $cache, $l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
103
104                 $this->app            = $app;
105                 $this->timeline       = $timeline;
106                 $this->systemMessages = $systemMessages;
107                 $this->conversation   = $conversation;
108                 $this->page           = $page;
109         }
110
111         protected function content(array $request = []): string
112         {
113                 if (!$this->session->getLocalUserId()) {
114                         return Login::form();
115                 }
116
117                 $this->parseRequest($request);
118
119                 $module = 'network';
120
121                 $arr = ['query' => $this->args->getQueryString()];
122                 Hook::callAll('network_content_init', $arr);
123
124                 $o = '';
125
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();
130                 } else {
131                         $items = $this->getItems();
132                 }
133
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', '');
142
143                 if (Feature::isEnabled($this->session->getLocalUserId(), 'trending_tags')) {
144                         $this->page['aside'] .= TrendingTags::getHTML($this->selectedTab);
145                 }
146
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()]);
150                 }
151
152                 if (!(isset($_GET['mode']) and ($_GET['mode'] == 'raw'))) {
153                         $o .= $this->getTabsHTML();
154
155                         Nav::setSelected($this->args->get(0));
156
157                         $content = '';
158
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'];
165                                 }
166                         }
167
168                         $default_permissions = [];
169                         if ($this->circleId) {
170                                 $default_permissions['allow_gid'] = [$this->circleId];
171                         }
172
173                         $allowedCids = [];
174                         if ($this->groupContactId) {
175                                 $allowedCids[] = (int) $this->groupContactId;
176                         } elseif ($this->network) {
177                                 $condition = [
178                                         'uid'     => $this->session->getLocalUserId(),
179                                         'network' => $this->network,
180                                         'self'    => false,
181                                         'blocked' => false,
182                                         'pending' => false,
183                                         'archive' => false,
184                                         'rel'     => [Contact::SHARING, Contact::FRIEND],
185                                 ];
186                                 $contactStmt = $this->database->select('contact', ['id'], $condition);
187                                 while ($contact = $this->database->fetch($contactStmt)) {
188                                         $allowedCids[] = (int) $contact['id'];
189                                 }
190                                 $this->database->close($contactStmt);
191                         }
192
193                         if (count($allowedCids)) {
194                                 $default_permissions['allow_cid'] = $allowedCids;
195                         }
196
197                         $x = [
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,
202                         ];
203
204                         $o .= $this->conversation->statusEditor($x);
205                 }
206
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'));
211                         }
212
213                         $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
214                                 '$title' => $this->l10n->t('Circle: %s', $circle['name'])
215                         ]) . $o;
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),
222                                 ]) . $o;
223                         } else {
224                                 $this->systemMessages->addNotice($this->l10n->t('Invalid contact.'));
225                         }
226                 } elseif (!$this->config->get('theme', 'hide_eventlist')) {
227                         $o .= Profile::getBirthdays();
228                         $o .= Profile::getEventsReminderHTML();
229                 }
230
231                 $o .= $this->conversation->render($items, Conversation::MODE_NETWORK, false, false, $this->getOrder(), $this->session->getLocalUserId());
232
233                 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
234                         $o .= HTML::scrollLoader();
235                 } else {
236                         $pager = new BoundariesPager(
237                                 $this->l10n,
238                                 $this->args->getQueryString(),
239                                 $items[0][$this->order] ?? null,
240                                 $items[count($items) - 1][$this->order] ?? null,
241                                 $this->itemsPerPage
242                         );
243
244                         $o .= $pager->renderMinimal(count($items));
245                 }
246
247                 return $o;
248         }
249
250         protected function getOrder(): string
251         {
252                 if ($this->order === 'received') {
253                         return '`received`';
254                 } elseif ($this->order === 'created') {
255                         return '`created`';
256                 } else {
257                         return '`commented`';
258                 }
259         }
260
261         /**
262          * Get the network tabs menu
263          *
264          * @return string Html of the network tabs
265          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
266          */
267         private function getTabsHTML()
268         {
269                 $tabs = $this->getTabArray($this->timeline->getNetworkFeeds($this->args->getCommand()), 'network');
270
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'));
275                 }
276
277                 $arr = ['tabs' => $tabs];
278                 Hook::callAll('network_tabs', $arr);
279
280                 if (!empty($network_timelines)) {
281                         $tabs = [];
282
283                         foreach ($arr['tabs'] as $tab) {
284                                 if (in_array($tab['code'], $network_timelines)) {
285                                         $tabs[] = $tab;
286                                 }
287                         }
288                 } else {
289                         $tabs = $arr['tabs'];
290                 }
291
292                 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
293
294                 return Renderer::replaceMacros($tpl, ['$tabs' => $tabs]);
295         }
296
297         protected function parseRequest(array $request)
298         {
299                 parent::parseRequest($request);
300
301                 $this->circleId = (int)($this->parameters['circle_id'] ?? 0);
302
303                 $this->groupContactId = (int)($this->parameters['contact_id'] ?? 0);
304
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.'));
309                 }
310
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;
313                 }
314
315                 if (!empty($request['star'])) {
316                         $this->selectedTab = TimelineEntity::STAR;
317                         $this->star = true;
318                 } else {
319                         $this->star = $this->selectedTab == TimelineEntity::STAR;
320                 }
321
322                 if (!empty($request['mention'])) {
323                         $this->selectedTab = TimelineEntity::MENTION;
324                         $this->mention = true;
325                 } else {
326                         $this->mention = $this->selectedTab == TimelineEntity::MENTION;
327                 }
328
329                 if (!empty($request['order'])) {
330                         $this->selectedTab = $request['order'];
331                         $this->order = $request['order'];
332                         $this->star = false;
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';
338                 } else {
339                         $this->order = 'commented';
340                 }
341
342                 $this->selectedTab = $this->selectedTab ?? $this->order;
343
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;
350                 }
351
352                 // Prohibit combined usage of "star" and "mention"
353                 if ($this->selectedTab == TimelineEntity::STAR) {
354                         $this->mention = false;
355                 } elseif ($this->selectedTab == TimelineEntity::MENTION) {
356                         $this->star = false;
357                 }
358
359                 $this->session->set('network-tab', $this->selectedTab);
360                 $this->pConfig->set($this->session->getLocalUserId(), 'network.view', 'selected_tab', $this->selectedTab);
361
362                 $this->network = $request['nets'] ?? '';
363
364                 $this->dateFrom = $this->parameters['from'] ?? '';
365                 $this->dateTo = $this->parameters['to'] ?? '';
366
367                 switch ($this->order) {
368                         case 'received':
369                                 $this->maxId = $request['last_received'] ?? $this->maxId;
370                                 $this->minId = $request['first_received'] ?? $this->minId;
371                                 break;
372                         case 'created':
373                                 $this->maxId = $request['last_created'] ?? $this->maxId;
374                                 $this->minId = $request['first_created'] ?? $this->minId;
375                                 break;
376                         case 'uriid':
377                                 $this->maxId = $request['last_uriid'] ?? $this->maxId;
378                                 $this->minId = $request['first_uriid'] ?? $this->minId;
379                                 break;
380                         default:
381                                 $this->order = 'commented';
382                                 $this->maxId = $request['last_commented'] ?? $this->maxId;
383                                 $this->minId = $request['first_commented'] ?? $this->minId;
384                 }
385         }
386
387         protected function getItems()
388         {
389                 $conditionFields  = ['uid' => $this->session->getLocalUserId()];
390                 $conditionStrings = [];
391
392                 if (!is_null($this->accountType)) {
393                         $conditionFields['contact-type'] = $this->accountType;
394                 }
395
396                 if ($this->star) {
397                         $conditionFields['starred'] = true;
398                 }
399                 if ($this->mention) {
400                         $conditionFields['mention'] = true;
401                 }
402                 if ($this->network) {
403                         $conditionFields['network'] = $this->network;
404                 }
405
406                 if ($this->dateFrom) {
407                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` <= ? ", DateTimeFormat::convert($this->dateFrom, 'UTC', $this->app->getTimeZone())]);
408                 }
409                 if ($this->dateTo) {
410                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` >= ? ", DateTimeFormat::convert($this->dateTo, 'UTC', $this->app->getTimeZone())]);
411                 }
412
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()]);
419                 }
420
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]);
424                 } else {
425                         if (isset($this->maxId)) {
426                                 switch ($this->order) {
427                                         case 'received':
428                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` < ?", $this->maxId]);
429                                                 break;
430                                         case 'commented':
431                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` < ?", $this->maxId]);
432                                                 break;
433                                         case 'created':
434                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` < ?", $this->maxId]);
435                                                 break;
436                                         case 'uriid':
437                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` < ?", $this->maxId]);
438                                                 break;
439                                 }
440                         }
441
442                         if (isset($this->minId)) {
443                                 switch ($this->order) {
444                                         case 'received':
445                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` > ?", $this->minId]);
446                                                 break;
447                                         case 'commented':
448                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` > ?", $this->minId]);
449                                                 break;
450                                         case 'created':
451                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` > ?", $this->minId]);
452                                                 break;
453                                         case 'uriid':
454                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` > ?", $this->minId]);
455                                                 break;
456                                 }
457                         }
458                 }
459
460                 $params = ['limit' => $this->itemsPerPage];
461
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];
467                 } else {
468                         $params['order'] = [$this->order => true];
469                 }
470
471                 $items = $this->database->selectToArray('network-thread-view', [], DBA::mergeConditions($conditionFields, $conditionStrings), $params);
472
473                 // min_id quirk, continued
474                 if (isset($this->minId) && !isset($this->maxId)) {
475                         $items = array_reverse($items);
476                 }
477
478                 if ($this->database->isResult($items)) {
479                         $parents = array_column($items, 'uri-id');
480                 } else {
481                         $parents = [];
482                 }
483
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);
493                 }
494
495                 return $items;
496         }
497
498         /**
499          * Returns the selected network tab of the currently logged-in user
500          *
501          * @param IHandleUserSessions         $session
502          * @param IManagePersonalConfigValues $pconfig
503          * @return string
504          */
505         public static function getTimelineOrderBySession(IHandleUserSessions $session, IManagePersonalConfigValues $pconfig): string
506         {
507                 return $session->get('network-tab')
508                         ?? $pconfig->get($session->getLocalUserId(), 'network.view', 'selected_tab')
509                         ?? '';
510         }
511 }