]> git.mxchange.org Git - friendica.git/blob - src/Module/Conversation/Network.php
Merge remote-tracking branch 'upstream/develop' into channel-languages
[friendica.git] / src / Module / Conversation / Network.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2024, 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\Profile;
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 Psr\Log\LoggerInterface;
61
62 class Network extends Timeline
63 {
64         /** @var int */
65         protected $circleId;
66         /** @var string */
67         protected $network;
68         /** @var string */
69         protected $dateFrom;
70         /** @var string */
71         protected $dateTo;
72         /** @var int */
73         protected $star;
74         /** @var int */
75         protected $mention;
76         /** @var string */
77         protected $order;
78
79         /** @var App */
80         protected $app;
81         /** @var ICanCache */
82         protected $cache;
83         /** @var IManageConfigValues The config */
84         protected $config;
85         /** @var SystemMessages */
86         protected $systemMessages;
87         /** @var App\Page */
88         protected $page;
89         /** @var Conversation */
90         protected $conversation;
91         /** @var IManagePersonalConfigValues */
92         protected $pConfig;
93         /** @var Database */
94         protected $database;
95         /** @var TimelineFactory */
96         protected $timeline;
97         /** @var ChannelFactory */
98         protected $channel;
99         /** @var UserDefinedChannelFactory */
100         protected $userDefinedChannel;
101         /** @var CommunityFactory */
102         protected $community;
103         /** @var NetworkFactory */
104         protected $networkFactory;
105
106         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 = [])
107         {
108                 parent::__construct($channel, $mode, $session, $database, $pConfig, $config, $cache, $l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
109
110                 $this->app                = $app;
111                 $this->timeline           = $timeline;
112                 $this->systemMessages     = $systemMessages;
113                 $this->conversation       = $conversation;
114                 $this->page               = $page;
115                 $this->channel            = $channelFactory;
116                 $this->community          = $community;
117                 $this->networkFactory     = $network;
118                 $this->userDefinedChannel = $userDefinedChannel;
119         }
120
121         protected function content(array $request = []): string
122         {
123                 if (!$this->session->getLocalUserId()) {
124                         return Login::form();
125                 }
126
127                 $this->parseRequest($request);
128
129                 $module = 'network';
130
131                 $arr = ['query' => $this->args->getQueryString()];
132                 Hook::callAll('network_content_init', $arr);
133
134                 $o = '';
135
136                 $this->page['aside'] .= Circle::sidebarWidget($module, $module . '/circle', 'standard', $this->circleId);
137                 $this->page['aside'] .= GroupManager::widget($this->session->getLocalUserId());
138                 $this->page['aside'] .= Widget::postedByYear($module . '/archive', $this->session->getLocalUserId(), false);
139                 $this->page['aside'] .= Widget::networks($module, $this->network);
140                 $this->page['aside'] .= Widget::accountTypes($module, $this->accountTypeString);
141                 $this->page['aside'] .= Widget::channels($module, $this->selectedTab, $this->session->getLocalUserId());
142                 $this->page['aside'] .= Widget\SavedSearches::getHTML($this->args->getQueryString());
143                 $this->page['aside'] .= Widget::fileAs('filed', '');
144
145                 if (Feature::isEnabled($this->session->getLocalUserId(), 'trending_tags')) {
146                         $this->page['aside'] .= TrendingTags::getHTML($this->selectedTab);
147                 }
148
149                 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll') && ($_GET['mode'] ?? '') != 'minimal') {
150                         $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
151                         $o .= Renderer::replaceMacros($tpl, ['$reload_uri' => $this->args->getQueryString()]);
152                 }
153
154                 if (!$this->raw) {
155                         $o .= $this->getTabsHTML();
156
157                         Nav::setSelected($this->args->get(0));
158
159                         $content = '';
160
161                         $default_permissions = [];
162                         if ($this->circleId) {
163                                 $default_permissions['allow_gid'] = [$this->circleId];
164                         }
165
166                         $allowedCids = [];
167                         if ($this->network) {
168                                 $condition = [
169                                         'uid'     => $this->session->getLocalUserId(),
170                                         'network' => $this->network,
171                                         'self'    => false,
172                                         'blocked' => false,
173                                         'pending' => false,
174                                         'archive' => false,
175                                         'rel'     => [Contact::SHARING, Contact::FRIEND],
176                                 ];
177                                 $contactStmt = $this->database->select('contact', ['id'], $condition);
178                                 while ($contact = $this->database->fetch($contactStmt)) {
179                                         $allowedCids[] = (int) $contact['id'];
180                                 }
181                                 $this->database->close($contactStmt);
182                         }
183
184                         if (count($allowedCids)) {
185                                 $default_permissions['allow_cid'] = $allowedCids;
186                         }
187
188                         $x = [
189                                 'lockstate' => $this->circleId || $this->network || ACL::getLockstateForUserId($this->session->getLocalUserId()) ? 'lock' : 'unlock',
190                                 'acl' => ACL::getFullSelectorHTML($this->page, $this->session->getLocalUserId(), true, $default_permissions),
191                                 'bang' => (($this->circleId || $this->network) ? '!' : ''),
192                                 'content' => $content,
193                         ];
194
195                         $o .= $this->conversation->statusEditor($x);
196
197                         if ($this->circleId) {
198                                 $circle = $this->database->selectFirst('group', ['name'], ['id' => $this->circleId, 'uid' => $this->session->getLocalUserId()]);
199                                 if (!$this->database->isResult($circle)) {
200                                         $this->systemMessages->addNotice($this->l10n->t('No such circle'));
201                                 }
202
203                                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
204                                         '$title' => $this->l10n->t('Circle: %s', $circle['name'])
205                                 ]) . $o;
206                         } elseif (Profile::shouldDisplayEventList($this->session->getLocalUserId(), $this->mode)) {
207                                 $o .= Profile::getBirthdays($this->session->getLocalUserId());
208                                 $o .= Profile::getEventsReminderHTML($this->session->getLocalUserId(), $this->session->getPublicContactId());
209                         }
210                 }
211
212                 try {
213                         if ($this->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId())) {
214                                 $items = $this->getChannelItems();
215                         } elseif ($this->community->isTimeline($this->selectedTab)) {
216                                 $items = $this->getCommunityItems();
217                         } else {
218                                 $items = $this->getItems();
219                         }
220         
221                         $o .= $this->conversation->render($items, Conversation::MODE_NETWORK, false, false, $this->getOrder(), $this->session->getLocalUserId());
222                 } catch (\Exception $e) {
223                         $o .= $this->l10n->t('Error %d (%s) while fetching the timeline.', $e->getCode(), $e->getMessage());
224                 }
225
226                 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
227                         $o .= HTML::scrollLoader();
228                 } else {
229                         $pager = new BoundariesPager(
230                                 $this->l10n,
231                                 $this->args->getQueryString(),
232                                 $items[0][$this->order] ?? null,
233                                 $items[count($items) - 1][$this->order] ?? null,
234                                 $this->itemsPerPage
235                         );
236
237                         $o .= $pager->renderMinimal(count($items));
238                 }
239
240                 return $o;
241         }
242
243         protected function getOrder(): string
244         {
245                 if ($this->order === 'received') {
246                         return '`received`';
247                 } elseif ($this->order === 'created') {
248                         return '`created`';
249                 } else {
250                         return '`commented`';
251                 }
252         }
253
254         /**
255          * Get the network tabs menu
256          *
257          * @return string Html of the network tabs
258          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
259          */
260         private function getTabsHTML()
261         {
262                 $tabs = $this->getTabArray($this->networkFactory->getTimelines($this->args->getCommand()), 'network');
263
264                 $network_timelines = $this->pConfig->get($this->session->getLocalUserId(), 'system', 'network_timelines', []);
265                 if (!empty($network_timelines)) {
266                         $tabs = array_merge($tabs, $this->getTabArray($this->channel->getTimelines($this->session->getLocalUserId()), 'network', 'channel'));
267                         $tabs = array_merge($tabs, $this->getTabArray($this->channelRepository->selectByUid($this->session->getLocalUserId()), 'network', 'channel'));
268                         $tabs = array_merge($tabs, $this->getTabArray($this->community->getTimelines(true), 'network', 'channel'));
269                 }
270
271                 $arr = ['tabs' => $tabs];
272                 Hook::callAll('network_tabs', $arr);
273
274                 if (!empty($network_timelines)) {
275                         $tabs = [];
276
277                         foreach ($arr['tabs'] as $tab) {
278                                 if (in_array($tab['code'], $network_timelines)) {
279                                         $tabs[] = $tab;
280                                 }
281                         }
282                 } else {
283                         $tabs = $arr['tabs'];
284                 }
285
286                 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
287
288                 return Renderer::replaceMacros($tpl, ['$tabs' => $tabs]);
289         }
290
291         protected function parseRequest(array $request)
292         {
293                 parent::parseRequest($request);
294
295                 $this->circleId = (int)($this->parameters['circle_id'] ?? 0);
296
297                 if (!$this->selectedTab) {
298                         $this->selectedTab = self::getTimelineOrderBySession($this->session, $this->pConfig);
299                 } elseif (!$this->networkFactory->isTimeline($this->selectedTab) && !$this->channel->isTimeline($this->selectedTab) && !$this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId()) && !$this->community->isTimeline($this->selectedTab)) {
300                         throw new HTTPException\BadRequestException($this->l10n->t('Network feed not available.'));
301                 }
302
303                 if (($this->network || $this->circleId) && ($this->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId()) || $this->community->isTimeline($this->selectedTab))) {
304                         $this->selectedTab = NetworkEntity::RECEIVED;
305                 }
306
307                 if (!empty($request['star'])) {
308                         $this->selectedTab = NetworkEntity::STAR;
309                         $this->star = true;
310                 } else {
311                         $this->star = $this->selectedTab == NetworkEntity::STAR;
312                 }
313
314                 if (!empty($request['mention'])) {
315                         $this->selectedTab = NetworkEntity::MENTION;
316                         $this->mention = true;
317                 } else {
318                         $this->mention = $this->selectedTab == NetworkEntity::MENTION;
319                 }
320
321                 if (!empty($request['order'])) {
322                         $this->selectedTab = $request['order'];
323                         $this->order = $request['order'];
324                         $this->star = false;
325                         $this->mention = false;
326                 } elseif (in_array($this->selectedTab, [NetworkEntity::RECEIVED, NetworkEntity::STAR]) || $this->community->isTimeline($this->selectedTab)) {
327                         $this->order = 'received';
328                 } elseif (($this->selectedTab == NetworkEntity::CREATED) || $this->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId())) {
329                         $this->order = 'created';
330                 } else {
331                         $this->order = 'commented';
332                 }
333
334                 $this->selectedTab = $this->selectedTab ?? $this->order;
335
336                 // Upon updates in the background and order by last comment we order by received date,
337                 // since otherwise the feed will optically jump, when some already visible thread has been updated.
338                 if ($this->update && ($this->selectedTab == NetworkEntity::COMMENTED)) {
339                         $this->order = 'received';
340                         $request['last_received']  = $request['last_commented'] ?? null;
341                         $request['first_received'] = $request['first_commented'] ?? null;
342                 }
343
344                 // Prohibit combined usage of "star" and "mention"
345                 if ($this->selectedTab == NetworkEntity::STAR) {
346                         $this->mention = false;
347                 } elseif ($this->selectedTab == NetworkEntity::MENTION) {
348                         $this->star = false;
349                 }
350
351                 $this->session->set('network-tab', $this->selectedTab);
352                 $this->pConfig->set($this->session->getLocalUserId(), 'network.view', 'selected_tab', $this->selectedTab);
353
354                 $this->network = $request['nets'] ?? '';
355
356                 $this->dateFrom = $this->parameters['from'] ?? '';
357                 $this->dateTo = $this->parameters['to'] ?? '';
358
359                 switch ($this->order) {
360                         case 'received':
361                                 $this->maxId = $request['last_received'] ?? $this->maxId;
362                                 $this->minId = $request['first_received'] ?? $this->minId;
363                                 break;
364                         case 'created':
365                                 $this->maxId = $request['last_created'] ?? $this->maxId;
366                                 $this->minId = $request['first_created'] ?? $this->minId;
367                                 break;
368                         case 'uriid':
369                                 $this->maxId = $request['last_uriid'] ?? $this->maxId;
370                                 $this->minId = $request['first_uriid'] ?? $this->minId;
371                                 break;
372                         default:
373                                 $this->order = 'commented';
374                                 $this->maxId = $request['last_commented'] ?? $this->maxId;
375                                 $this->minId = $request['first_commented'] ?? $this->minId;
376                 }
377         }
378
379         protected function getItems()
380         {
381                 $conditionFields  = ['uid' => $this->session->getLocalUserId()];
382                 $conditionStrings = [];
383
384                 if (!is_null($this->accountType)) {
385                         $conditionFields['contact-type'] = $this->accountType;
386                 }
387
388                 if ($this->star) {
389                         $conditionFields['starred'] = true;
390                 }
391                 if ($this->mention) {
392                         $conditionFields['mention'] = true;
393                 }
394                 if ($this->network) {
395                         $conditionFields['network'] = $this->network;
396                 }
397
398                 if ($this->dateFrom) {
399                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` <= ? ", DateTimeFormat::convert($this->dateFrom, 'UTC', $this->app->getTimeZone())]);
400                 }
401                 if ($this->dateTo) {
402                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` >= ? ", DateTimeFormat::convert($this->dateTo, 'UTC', $this->app->getTimeZone())]);
403                 }
404
405                 if ($this->circleId) {
406                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`contact-id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)", $this->circleId]);
407                 }
408
409                 // Currently only the order modes "received" and "commented" are in use
410                 if (!empty($this->itemUriId)) {
411                         $conditionStrings = DBA::mergeConditions($conditionStrings, ['uri-id' => $this->itemUriId]);
412                 } else {
413                         if (isset($this->maxId)) {
414                                 switch ($this->order) {
415                                         case 'received':
416                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` < ?", $this->maxId]);
417                                                 break;
418                                         case 'commented':
419                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` < ?", $this->maxId]);
420                                                 break;
421                                         case 'created':
422                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` < ?", $this->maxId]);
423                                                 break;
424                                         case 'uriid':
425                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` < ?", $this->maxId]);
426                                                 break;
427                                 }
428                         }
429
430                         if (isset($this->minId)) {
431                                 switch ($this->order) {
432                                         case 'received':
433                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` > ?", $this->minId]);
434                                                 break;
435                                         case 'commented':
436                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` > ?", $this->minId]);
437                                                 break;
438                                         case 'created':
439                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` > ?", $this->minId]);
440                                                 break;
441                                         case 'uriid':
442                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` > ?", $this->minId]);
443                                                 break;
444                                 }
445                         }
446                 }
447
448                 $params = ['limit' => $this->itemsPerPage];
449
450                 if (isset($this->minId) && !isset($this->maxId)) {
451                         // min_id quirk: querying in reverse order with min_id gets the most recent rows, regardless of how close
452                         // they are to min_id. We change the query ordering to get the expected data, and we need to reverse the
453                         // order of the results.
454                         $params['order'] = [$this->order => false];
455                 } else {
456                         $params['order'] = [$this->order => true];
457                 }
458
459                 $items = $this->database->selectToArray('network-thread-view', [], DBA::mergeConditions($conditionFields, $conditionStrings), $params);
460
461                 // min_id quirk, continued
462                 if (isset($this->minId) && !isset($this->maxId)) {
463                         $items = array_reverse($items);
464                 }
465
466                 if ($this->database->isResult($items)) {
467                         $parents = array_column($items, 'uri-id');
468                 } else {
469                         $parents = [];
470                 }
471
472                 // We aren't going to try and figure out at the item, circle, and page
473                 // level which items you've seen and which you haven't. If you're looking
474                 // at the top level network page just mark everything seen.
475                 if (!$this->circleId && !$this->star && !$this->mention) {
476                         $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId()];
477                         $this->setItemsSeenByCondition($condition);
478                 } elseif (!empty($parents)) {
479                         $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => $parents];
480                         $this->setItemsSeenByCondition($condition);
481                 }
482
483                 return $items;
484         }
485
486         /**
487          * Returns the selected network tab of the currently logged-in user
488          *
489          * @param IHandleUserSessions         $session
490          * @param IManagePersonalConfigValues $pconfig
491          * @return string
492          */
493         public static function getTimelineOrderBySession(IHandleUserSessions $session, IManagePersonalConfigValues $pconfig): string
494         {
495                 return $session->get('network-tab')
496                         ?? $pconfig->get($session->getLocalUserId(), 'network.view', 'selected_tab')
497                         ?? '';
498         }
499 }