]> git.mxchange.org Git - friendica.git/blob - src/Module/Conversation/Network.php
Merge branch '2023.09-rc' into move-mentionbutton-to-navbar
[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\Network as NetworkEntity;
29 use Friendica\Content\Conversation\Factory\Timeline as TimelineFactory;
30 use Friendica\Content\Conversation\Repository\UserDefinedChannel;
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;
65
66 class Network extends Timeline
67 {
68         /** @var int */
69         protected $circleId;
70         /** @var int */
71         protected $groupContactId;
72         /** @var string */
73         protected $network;
74         /** @var string */
75         protected $dateFrom;
76         /** @var string */
77         protected $dateTo;
78         /** @var int */
79         protected $star;
80         /** @var int */
81         protected $mention;
82         /** @var string */
83         protected $order;
84
85         /** @var App */
86         protected $app;
87         /** @var ICanCache */
88         protected $cache;
89         /** @var IManageConfigValues The config */
90         protected $config;
91         /** @var SystemMessages */
92         protected $systemMessages;
93         /** @var App\Page */
94         protected $page;
95         /** @var Conversation */
96         protected $conversation;
97         /** @var IManagePersonalConfigValues */
98         protected $pConfig;
99         /** @var Database */
100         protected $database;
101         /** @var TimelineFactory */
102         protected $timeline;
103         /** @var ChannelFactory */
104         protected $channel;
105         /** @var UserDefinedChannelFactory */
106         protected $userDefinedChannel;
107         /** @var CommunityFactory */
108         protected $community;
109         /** @var NetworkFactory */
110         protected $networkFactory;
111
112         public function __construct(UserDefinedChannelFactory $userDefinedChannel, NetworkFactory $network, CommunityFactory $community, ChannelFactory $channelFactory, UserDefinedChannel $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 = [])
113         {
114                 parent::__construct($channel, $mode, $session, $database, $pConfig, $config, $cache, $l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
115
116                 $this->app                = $app;
117                 $this->timeline           = $timeline;
118                 $this->systemMessages     = $systemMessages;
119                 $this->conversation       = $conversation;
120                 $this->page               = $page;
121                 $this->channel            = $channelFactory;
122                 $this->community          = $community;
123                 $this->networkFactory     = $network;
124                 $this->userDefinedChannel = $userDefinedChannel;
125         }
126
127         protected function content(array $request = []): string
128         {
129                 if (!$this->session->getLocalUserId()) {
130                         return Login::form();
131                 }
132
133                 $this->parseRequest($request);
134
135                 $module = 'network';
136
137                 $arr = ['query' => $this->args->getQueryString()];
138                 Hook::callAll('network_content_init', $arr);
139
140                 $o = '';
141
142                 if ($this->channel->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();
146                 } else {
147                         $items = $this->getItems();
148                 }
149
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', '');
158
159                 if (Feature::isEnabled($this->session->getLocalUserId(), 'trending_tags')) {
160                         $this->page['aside'] .= TrendingTags::getHTML($this->selectedTab);
161                 }
162
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()]);
166                 }
167
168                 if (!(isset($_GET['mode']) and ($_GET['mode'] == 'raw'))) {
169                         $o .= $this->getTabsHTML();
170
171                         Nav::setSelected($this->args->get(0));
172
173                         $content = '';
174
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'];
181                                 }
182                         }
183
184                         $default_permissions = [];
185                         if ($this->circleId) {
186                                 $default_permissions['allow_gid'] = [$this->circleId];
187                         }
188
189                         $allowedCids = [];
190                         if ($this->groupContactId) {
191                                 $allowedCids[] = (int) $this->groupContactId;
192                         } elseif ($this->network) {
193                                 $condition = [
194                                         'uid'     => $this->session->getLocalUserId(),
195                                         'network' => $this->network,
196                                         'self'    => false,
197                                         'blocked' => false,
198                                         'pending' => false,
199                                         'archive' => false,
200                                         'rel'     => [Contact::SHARING, Contact::FRIEND],
201                                 ];
202                                 $contactStmt = $this->database->select('contact', ['id'], $condition);
203                                 while ($contact = $this->database->fetch($contactStmt)) {
204                                         $allowedCids[] = (int) $contact['id'];
205                                 }
206                                 $this->database->close($contactStmt);
207                         }
208
209                         if (count($allowedCids)) {
210                                 $default_permissions['allow_cid'] = $allowedCids;
211                         }
212
213                         $x = [
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,
218                         ];
219
220                         $o .= $this->conversation->statusEditor($x);
221                 }
222
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'));
227                         }
228
229                         $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
230                                 '$title' => $this->l10n->t('Circle: %s', $circle['name'])
231                         ]) . $o;
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),
238                                 ]) . $o;
239                         } else {
240                                 $this->systemMessages->addNotice($this->l10n->t('Invalid contact.'));
241                         }
242                 } elseif (!$this->config->get('theme', 'hide_eventlist')) {
243                         $o .= Profile::getBirthdays();
244                         $o .= Profile::getEventsReminderHTML();
245                 }
246
247                 $o .= $this->conversation->render($items, Conversation::MODE_NETWORK, false, false, $this->getOrder(), $this->session->getLocalUserId());
248
249                 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
250                         $o .= HTML::scrollLoader();
251                 } else {
252                         $pager = new BoundariesPager(
253                                 $this->l10n,
254                                 $this->args->getQueryString(),
255                                 $items[0][$this->order] ?? null,
256                                 $items[count($items) - 1][$this->order] ?? null,
257                                 $this->itemsPerPage
258                         );
259
260                         $o .= $pager->renderMinimal(count($items));
261                 }
262
263                 return $o;
264         }
265
266         protected function getOrder(): string
267         {
268                 if ($this->order === 'received') {
269                         return '`received`';
270                 } elseif ($this->order === 'created') {
271                         return '`created`';
272                 } else {
273                         return '`commented`';
274                 }
275         }
276
277         /**
278          * Get the network tabs menu
279          *
280          * @return string Html of the network tabs
281          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
282          */
283         private function getTabsHTML()
284         {
285                 $tabs = $this->getTabArray($this->networkFactory->getTimelines($this->args->getCommand()), 'network');
286
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->channel->getTimelines($this->session->getLocalUserId()), 'network', 'channel'));
290                         $tabs = array_merge($tabs, $this->getTabArray($this->channelRepository->selectByUid($this->session->getLocalUserId()), 'network', 'channel'));
291                         $tabs = array_merge($tabs, $this->getTabArray($this->community->getTimelines(true), 'network', 'channel'));
292                 }
293
294                 $arr = ['tabs' => $tabs];
295                 Hook::callAll('network_tabs', $arr);
296
297                 if (!empty($network_timelines)) {
298                         $tabs = [];
299
300                         foreach ($arr['tabs'] as $tab) {
301                                 if (in_array($tab['code'], $network_timelines)) {
302                                         $tabs[] = $tab;
303                                 }
304                         }
305                 } else {
306                         $tabs = $arr['tabs'];
307                 }
308
309                 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
310
311                 return Renderer::replaceMacros($tpl, ['$tabs' => $tabs]);
312         }
313
314         protected function parseRequest(array $request)
315         {
316                 parent::parseRequest($request);
317
318                 $this->circleId = (int)($this->parameters['circle_id'] ?? 0);
319
320                 $this->groupContactId = (int)($this->parameters['contact_id'] ?? 0);
321
322                 if (!$this->selectedTab) {
323                         $this->selectedTab = self::getTimelineOrderBySession($this->session, $this->pConfig);
324                 } elseif (!$this->networkFactory->isTimeline($this->selectedTab) && !$this->channel->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.'));
326                 }
327
328                 if (($this->network || $this->circleId || $this->groupContactId) && ($this->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId()) || $this->community->isTimeline($this->selectedTab))) {
329                         $this->selectedTab = NetworkEntity::RECEIVED;
330                 }
331
332                 if (!empty($request['star'])) {
333                         $this->selectedTab = NetworkEntity::STAR;
334                         $this->star = true;
335                 } else {
336                         $this->star = $this->selectedTab == NetworkEntity::STAR;
337                 }
338
339                 if (!empty($request['mention'])) {
340                         $this->selectedTab = NetworkEntity::MENTION;
341                         $this->mention = true;
342                 } else {
343                         $this->mention = $this->selectedTab == NetworkEntity::MENTION;
344                 }
345
346                 if (!empty($request['order'])) {
347                         $this->selectedTab = $request['order'];
348                         $this->order = $request['order'];
349                         $this->star = false;
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->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId())) {
354                         $this->order = 'created';
355                 } else {
356                         $this->order = 'commented';
357                 }
358
359                 $this->selectedTab = $this->selectedTab ?? $this->order;
360
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;
367                 }
368
369                 // Prohibit combined usage of "star" and "mention"
370                 if ($this->selectedTab == NetworkEntity::STAR) {
371                         $this->mention = false;
372                 } elseif ($this->selectedTab == NetworkEntity::MENTION) {
373                         $this->star = false;
374                 }
375
376                 $this->session->set('network-tab', $this->selectedTab);
377                 $this->pConfig->set($this->session->getLocalUserId(), 'network.view', 'selected_tab', $this->selectedTab);
378
379                 $this->network = $request['nets'] ?? '';
380
381                 $this->dateFrom = $this->parameters['from'] ?? '';
382                 $this->dateTo = $this->parameters['to'] ?? '';
383
384                 switch ($this->order) {
385                         case 'received':
386                                 $this->maxId = $request['last_received'] ?? $this->maxId;
387                                 $this->minId = $request['first_received'] ?? $this->minId;
388                                 break;
389                         case 'created':
390                                 $this->maxId = $request['last_created'] ?? $this->maxId;
391                                 $this->minId = $request['first_created'] ?? $this->minId;
392                                 break;
393                         case 'uriid':
394                                 $this->maxId = $request['last_uriid'] ?? $this->maxId;
395                                 $this->minId = $request['first_uriid'] ?? $this->minId;
396                                 break;
397                         default:
398                                 $this->order = 'commented';
399                                 $this->maxId = $request['last_commented'] ?? $this->maxId;
400                                 $this->minId = $request['first_commented'] ?? $this->minId;
401                 }
402         }
403
404         protected function getItems()
405         {
406                 $conditionFields  = ['uid' => $this->session->getLocalUserId()];
407                 $conditionStrings = [];
408
409                 if (!is_null($this->accountType)) {
410                         $conditionFields['contact-type'] = $this->accountType;
411                 }
412
413                 if ($this->star) {
414                         $conditionFields['starred'] = true;
415                 }
416                 if ($this->mention) {
417                         $conditionFields['mention'] = true;
418                 }
419                 if ($this->network) {
420                         $conditionFields['network'] = $this->network;
421                 }
422
423                 if ($this->dateFrom) {
424                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` <= ? ", DateTimeFormat::convert($this->dateFrom, 'UTC', $this->app->getTimeZone())]);
425                 }
426                 if ($this->dateTo) {
427                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` >= ? ", DateTimeFormat::convert($this->dateTo, 'UTC', $this->app->getTimeZone())]);
428                 }
429
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()]);
436                 }
437
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]);
441                 } else {
442                         if (isset($this->maxId)) {
443                                 switch ($this->order) {
444                                         case 'received':
445                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` < ?", $this->maxId]);
446                                                 break;
447                                         case 'commented':
448                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` < ?", $this->maxId]);
449                                                 break;
450                                         case 'created':
451                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` < ?", $this->maxId]);
452                                                 break;
453                                         case 'uriid':
454                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` < ?", $this->maxId]);
455                                                 break;
456                                 }
457                         }
458
459                         if (isset($this->minId)) {
460                                 switch ($this->order) {
461                                         case 'received':
462                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` > ?", $this->minId]);
463                                                 break;
464                                         case 'commented':
465                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` > ?", $this->minId]);
466                                                 break;
467                                         case 'created':
468                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` > ?", $this->minId]);
469                                                 break;
470                                         case 'uriid':
471                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` > ?", $this->minId]);
472                                                 break;
473                                 }
474                         }
475                 }
476
477                 $params = ['limit' => $this->itemsPerPage];
478
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];
484                 } else {
485                         $params['order'] = [$this->order => true];
486                 }
487
488                 $items = $this->database->selectToArray('network-thread-view', [], DBA::mergeConditions($conditionFields, $conditionStrings), $params);
489
490                 // min_id quirk, continued
491                 if (isset($this->minId) && !isset($this->maxId)) {
492                         $items = array_reverse($items);
493                 }
494
495                 if ($this->database->isResult($items)) {
496                         $parents = array_column($items, 'uri-id');
497                 } else {
498                         $parents = [];
499                 }
500
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);
510                 }
511
512                 return $items;
513         }
514
515         /**
516          * Returns the selected network tab of the currently logged-in user
517          *
518          * @param IHandleUserSessions         $session
519          * @param IManagePersonalConfigValues $pconfig
520          * @return string
521          */
522         public static function getTimelineOrderBySession(IHandleUserSessions $session, IManagePersonalConfigValues $pconfig): string
523         {
524                 return $session->get('network-tab')
525                         ?? $pconfig->get($session->getLocalUserId(), 'network.view', 'selected_tab')
526                         ?? '';
527         }
528 }