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