]> git.mxchange.org Git - friendica.git/blob - src/Module/Conversation/Network.php
Merge pull request #13635 from gudzpoz/emojis-please
[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                 $this->page['aside'] .= Circle::sidebarWidget($module, $module . '/circle', 'standard', $this->circleId);
143                 $this->page['aside'] .= GroupManager::widget($module . '/group', $this->session->getLocalUserId(), $this->groupContactId);
144                 $this->page['aside'] .= Widget::postedByYear($module . '/archive', $this->session->getLocalUserId(), false);
145                 $this->page['aside'] .= Widget::networks($module, !$this->groupContactId ? $this->network : '');
146                 $this->page['aside'] .= Widget::accountTypes($module, $this->accountTypeString);
147                 $this->page['aside'] .= Widget::channels($module, $this->selectedTab, $this->session->getLocalUserId());
148                 $this->page['aside'] .= Widget\SavedSearches::getHTML($this->args->getQueryString());
149                 $this->page['aside'] .= Widget::fileAs('filed', '');
150
151                 if (Feature::isEnabled($this->session->getLocalUserId(), 'trending_tags')) {
152                         $this->page['aside'] .= TrendingTags::getHTML($this->selectedTab);
153                 }
154
155                 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll') && ($_GET['mode'] ?? '') != 'minimal') {
156                         $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
157                         $o .= Renderer::replaceMacros($tpl, ['$reload_uri' => $this->args->getQueryString()]);
158                 }
159
160                 if (!(isset($_GET['mode']) and ($_GET['mode'] == 'raw'))) {
161                         $o .= $this->getTabsHTML();
162
163                         Nav::setSelected($this->args->get(0));
164
165                         $content = '';
166
167                         if ($this->groupContactId) {
168                                 // If $this->groupContactId belongs to a community group or a private group, add a mention to the status editor
169                                 $condition = ["`id` = ? AND `contact-type` = ?", $this->groupContactId, Contact::TYPE_COMMUNITY];
170                                 $contact = $this->database->selectFirst('contact', ['addr'], $condition);
171                                 if (!empty($contact['addr'])) {
172                                         $content = '!' . $contact['addr'];
173                                 }
174                         }
175
176                         $default_permissions = [];
177                         if ($this->circleId) {
178                                 $default_permissions['allow_gid'] = [$this->circleId];
179                         }
180
181                         $allowedCids = [];
182                         if ($this->groupContactId) {
183                                 $allowedCids[] = (int) $this->groupContactId;
184                         } elseif ($this->network) {
185                                 $condition = [
186                                         'uid'     => $this->session->getLocalUserId(),
187                                         'network' => $this->network,
188                                         'self'    => false,
189                                         'blocked' => false,
190                                         'pending' => false,
191                                         'archive' => false,
192                                         'rel'     => [Contact::SHARING, Contact::FRIEND],
193                                 ];
194                                 $contactStmt = $this->database->select('contact', ['id'], $condition);
195                                 while ($contact = $this->database->fetch($contactStmt)) {
196                                         $allowedCids[] = (int) $contact['id'];
197                                 }
198                                 $this->database->close($contactStmt);
199                         }
200
201                         if (count($allowedCids)) {
202                                 $default_permissions['allow_cid'] = $allowedCids;
203                         }
204
205                         $x = [
206                                 'lockstate' => $this->circleId || $this->groupContactId || $this->network || ACL::getLockstateForUserId($this->session->getLocalUserId()) ? 'lock' : 'unlock',
207                                 'acl' => ACL::getFullSelectorHTML($this->page, $this->session->getLocalUserId(), true, $default_permissions),
208                                 'bang' => (($this->circleId || $this->groupContactId || $this->network) ? '!' : ''),
209                                 'content' => $content,
210                         ];
211
212                         $o .= $this->conversation->statusEditor($x);
213                 }
214
215                 if ($this->circleId) {
216                         $circle = $this->database->selectFirst('group', ['name'], ['id' => $this->circleId, 'uid' => $this->session->getLocalUserId()]);
217                         if (!$this->database->isResult($circle)) {
218                                 $this->systemMessages->addNotice($this->l10n->t('No such circle'));
219                         }
220
221                         $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
222                                 '$title' => $this->l10n->t('Circle: %s', $circle['name'])
223                         ]) . $o;
224                 } elseif ($this->groupContactId) {
225                         $contact = Contact::getById($this->groupContactId);
226                         if ($this->database->isResult($contact)) {
227                                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('contact/list.tpl'), [
228                                         'contacts' => [ModuleContact::getContactTemplateVars($contact)],
229                                         'id' => $this->args->get(0),
230                                 ]) . $o;
231                         } else {
232                                 $this->systemMessages->addNotice($this->l10n->t('Invalid contact.'));
233                         }
234                 } elseif (!$this->config->get('theme', 'hide_eventlist')) {
235                         $o .= Profile::getBirthdays();
236                         $o .= Profile::getEventsReminderHTML();
237                 }
238
239                 try {
240                         if ($this->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId())) {
241                                 $items = $this->getChannelItems();
242                         } elseif ($this->community->isTimeline($this->selectedTab)) {
243                                 $items = $this->getCommunityItems();
244                         } else {
245                                 $items = $this->getItems();
246                         }
247         
248                         $o .= $this->conversation->render($items, Conversation::MODE_NETWORK, false, false, $this->getOrder(), $this->session->getLocalUserId());
249                 } catch (\Exception $e) {
250                         $o .= $this->l10n->t('Error %d (%s) while fetching the timeline.', $e->getCode(), $e->getMessage());
251                 }
252
253                 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
254                         $o .= HTML::scrollLoader();
255                 } else {
256                         $pager = new BoundariesPager(
257                                 $this->l10n,
258                                 $this->args->getQueryString(),
259                                 $items[0][$this->order] ?? null,
260                                 $items[count($items) - 1][$this->order] ?? null,
261                                 $this->itemsPerPage
262                         );
263
264                         $o .= $pager->renderMinimal(count($items));
265                 }
266
267                 return $o;
268         }
269
270         protected function getOrder(): string
271         {
272                 if ($this->order === 'received') {
273                         return '`received`';
274                 } elseif ($this->order === 'created') {
275                         return '`created`';
276                 } else {
277                         return '`commented`';
278                 }
279         }
280
281         /**
282          * Get the network tabs menu
283          *
284          * @return string Html of the network tabs
285          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
286          */
287         private function getTabsHTML()
288         {
289                 $tabs = $this->getTabArray($this->networkFactory->getTimelines($this->args->getCommand()), 'network');
290
291                 $network_timelines = $this->pConfig->get($this->session->getLocalUserId(), 'system', 'network_timelines', []);
292                 if (!empty($network_timelines)) {
293                         $tabs = array_merge($tabs, $this->getTabArray($this->channel->getTimelines($this->session->getLocalUserId()), 'network', 'channel'));
294                         $tabs = array_merge($tabs, $this->getTabArray($this->channelRepository->selectByUid($this->session->getLocalUserId()), 'network', 'channel'));
295                         $tabs = array_merge($tabs, $this->getTabArray($this->community->getTimelines(true), 'network', 'channel'));
296                 }
297
298                 $arr = ['tabs' => $tabs];
299                 Hook::callAll('network_tabs', $arr);
300
301                 if (!empty($network_timelines)) {
302                         $tabs = [];
303
304                         foreach ($arr['tabs'] as $tab) {
305                                 if (in_array($tab['code'], $network_timelines)) {
306                                         $tabs[] = $tab;
307                                 }
308                         }
309                 } else {
310                         $tabs = $arr['tabs'];
311                 }
312
313                 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
314
315                 return Renderer::replaceMacros($tpl, ['$tabs' => $tabs]);
316         }
317
318         protected function parseRequest(array $request)
319         {
320                 parent::parseRequest($request);
321
322                 $this->circleId = (int)($this->parameters['circle_id'] ?? 0);
323
324                 $this->groupContactId = (int)($this->parameters['contact_id'] ?? 0);
325
326                 if (!$this->selectedTab) {
327                         $this->selectedTab = self::getTimelineOrderBySession($this->session, $this->pConfig);
328                 } elseif (!$this->networkFactory->isTimeline($this->selectedTab) && !$this->channel->isTimeline($this->selectedTab) && !$this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId()) && !$this->community->isTimeline($this->selectedTab)) {
329                         throw new HTTPException\BadRequestException($this->l10n->t('Network feed not available.'));
330                 }
331
332                 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))) {
333                         $this->selectedTab = NetworkEntity::RECEIVED;
334                 }
335
336                 if (!empty($request['star'])) {
337                         $this->selectedTab = NetworkEntity::STAR;
338                         $this->star = true;
339                 } else {
340                         $this->star = $this->selectedTab == NetworkEntity::STAR;
341                 }
342
343                 if (!empty($request['mention'])) {
344                         $this->selectedTab = NetworkEntity::MENTION;
345                         $this->mention = true;
346                 } else {
347                         $this->mention = $this->selectedTab == NetworkEntity::MENTION;
348                 }
349
350                 if (!empty($request['order'])) {
351                         $this->selectedTab = $request['order'];
352                         $this->order = $request['order'];
353                         $this->star = false;
354                         $this->mention = false;
355                 } elseif (in_array($this->selectedTab, [NetworkEntity::RECEIVED, NetworkEntity::STAR]) || $this->community->isTimeline($this->selectedTab)) {
356                         $this->order = 'received';
357                 } elseif (($this->selectedTab == NetworkEntity::CREATED) || $this->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId())) {
358                         $this->order = 'created';
359                 } else {
360                         $this->order = 'commented';
361                 }
362
363                 $this->selectedTab = $this->selectedTab ?? $this->order;
364
365                 // Upon updates in the background and order by last comment we order by received date,
366                 // since otherwise the feed will optically jump, when some already visible thread has been updated.
367                 if ($this->update && ($this->selectedTab == NetworkEntity::COMMENTED)) {
368                         $this->order = 'received';
369                         $request['last_received']  = $request['last_commented'] ?? null;
370                         $request['first_received'] = $request['first_commented'] ?? null;
371                 }
372
373                 // Prohibit combined usage of "star" and "mention"
374                 if ($this->selectedTab == NetworkEntity::STAR) {
375                         $this->mention = false;
376                 } elseif ($this->selectedTab == NetworkEntity::MENTION) {
377                         $this->star = false;
378                 }
379
380                 $this->session->set('network-tab', $this->selectedTab);
381                 $this->pConfig->set($this->session->getLocalUserId(), 'network.view', 'selected_tab', $this->selectedTab);
382
383                 $this->network = $request['nets'] ?? '';
384
385                 $this->dateFrom = $this->parameters['from'] ?? '';
386                 $this->dateTo = $this->parameters['to'] ?? '';
387
388                 switch ($this->order) {
389                         case 'received':
390                                 $this->maxId = $request['last_received'] ?? $this->maxId;
391                                 $this->minId = $request['first_received'] ?? $this->minId;
392                                 break;
393                         case 'created':
394                                 $this->maxId = $request['last_created'] ?? $this->maxId;
395                                 $this->minId = $request['first_created'] ?? $this->minId;
396                                 break;
397                         case 'uriid':
398                                 $this->maxId = $request['last_uriid'] ?? $this->maxId;
399                                 $this->minId = $request['first_uriid'] ?? $this->minId;
400                                 break;
401                         default:
402                                 $this->order = 'commented';
403                                 $this->maxId = $request['last_commented'] ?? $this->maxId;
404                                 $this->minId = $request['first_commented'] ?? $this->minId;
405                 }
406         }
407
408         protected function getItems()
409         {
410                 $conditionFields  = ['uid' => $this->session->getLocalUserId()];
411                 $conditionStrings = [];
412
413                 if (!is_null($this->accountType)) {
414                         $conditionFields['contact-type'] = $this->accountType;
415                 }
416
417                 if ($this->star) {
418                         $conditionFields['starred'] = true;
419                 }
420                 if ($this->mention) {
421                         $conditionFields['mention'] = true;
422                 }
423                 if ($this->network) {
424                         $conditionFields['network'] = $this->network;
425                 }
426
427                 if ($this->dateFrom) {
428                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` <= ? ", DateTimeFormat::convert($this->dateFrom, 'UTC', $this->app->getTimeZone())]);
429                 }
430                 if ($this->dateTo) {
431                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` >= ? ", DateTimeFormat::convert($this->dateTo, 'UTC', $this->app->getTimeZone())]);
432                 }
433
434                 if ($this->circleId) {
435                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`contact-id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)", $this->circleId]);
436                 } elseif ($this->groupContactId) {
437                         $conditionStrings = DBA::mergeConditions($conditionStrings,
438                                 ["((`contact-id` = ?) OR `uri-id` IN (SELECT `parent-uri-id` FROM `post-user-view` WHERE (`contact-id` = ? AND `gravity` = ? AND `vid` = ? AND `uid` = ?)))",
439                                 $this->groupContactId, $this->groupContactId, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), $this->session->getLocalUserId()]);
440                 }
441
442                 // Currently only the order modes "received" and "commented" are in use
443                 if (!empty($this->itemUriId)) {
444                         $conditionStrings = DBA::mergeConditions($conditionStrings, ['uri-id' => $this->itemUriId]);
445                 } else {
446                         if (isset($this->maxId)) {
447                                 switch ($this->order) {
448                                         case 'received':
449                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` < ?", $this->maxId]);
450                                                 break;
451                                         case 'commented':
452                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` < ?", $this->maxId]);
453                                                 break;
454                                         case 'created':
455                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` < ?", $this->maxId]);
456                                                 break;
457                                         case 'uriid':
458                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` < ?", $this->maxId]);
459                                                 break;
460                                 }
461                         }
462
463                         if (isset($this->minId)) {
464                                 switch ($this->order) {
465                                         case 'received':
466                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` > ?", $this->minId]);
467                                                 break;
468                                         case 'commented':
469                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` > ?", $this->minId]);
470                                                 break;
471                                         case 'created':
472                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` > ?", $this->minId]);
473                                                 break;
474                                         case 'uriid':
475                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` > ?", $this->minId]);
476                                                 break;
477                                 }
478                         }
479                 }
480
481                 $params = ['limit' => $this->itemsPerPage];
482
483                 if (isset($this->minId) && !isset($this->maxId)) {
484                         // min_id quirk: querying in reverse order with min_id gets the most recent rows, regardless of how close
485                         // they are to min_id. We change the query ordering to get the expected data, and we need to reverse the
486                         // order of the results.
487                         $params['order'] = [$this->order => false];
488                 } else {
489                         $params['order'] = [$this->order => true];
490                 }
491
492                 $items = $this->database->selectToArray('network-thread-view', [], DBA::mergeConditions($conditionFields, $conditionStrings), $params);
493
494                 // min_id quirk, continued
495                 if (isset($this->minId) && !isset($this->maxId)) {
496                         $items = array_reverse($items);
497                 }
498
499                 if ($this->database->isResult($items)) {
500                         $parents = array_column($items, 'uri-id');
501                 } else {
502                         $parents = [];
503                 }
504
505                 // We aren't going to try and figure out at the item, circle, and page
506                 // level which items you've seen and which you haven't. If you're looking
507                 // at the top level network page just mark everything seen.
508                 if (!$this->circleId && !$this->groupContactId && !$this->star && !$this->mention) {
509                         $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId()];
510                         $this->setItemsSeenByCondition($condition);
511                 } elseif (!empty($parents)) {
512                         $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => $parents];
513                         $this->setItemsSeenByCondition($condition);
514                 }
515
516                 return $items;
517         }
518
519         /**
520          * Returns the selected network tab of the currently logged-in user
521          *
522          * @param IHandleUserSessions         $session
523          * @param IManagePersonalConfigValues $pconfig
524          * @return string
525          */
526         public static function getTimelineOrderBySession(IHandleUserSessions $session, IManagePersonalConfigValues $pconfig): string
527         {
528                 return $session->get('network-tab')
529                         ?? $pconfig->get($session->getLocalUserId(), 'network.view', 'selected_tab')
530                         ?? '';
531         }
532 }