]> git.mxchange.org Git - friendica.git/blob - src/Module/Conversation/Network.php
Fix "received"
[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\Model\Contact;
47 use Friendica\Model\Circle;
48 use Friendica\Model\Item;
49 use Friendica\Model\Profile;
50 use Friendica\Model\Verb;
51 use Friendica\Module\Contact as ModuleContact;
52 use Friendica\Module\Response;
53 use Friendica\Module\Security\Login;
54 use Friendica\Network\HTTPException;
55 use Friendica\Navigation\SystemMessages;
56 use Friendica\Util\DateTimeFormat;
57 use Friendica\Util\Profiler;
58 use Friendica\Protocol\Activity;
59 use Psr\Log\LoggerInterface;
60
61 class Network extends Timeline
62 {
63         /** @var int */
64         protected $circleId;
65         /** @var int */
66         protected $groupContactId;
67         /** @var string */
68         protected $network;
69         /** @var string */
70         protected $dateFrom;
71         /** @var string */
72         protected $dateTo;
73         /** @var int */
74         protected $star;
75         /** @var int */
76         protected $mention;
77         /** @var string */
78         protected $order;
79
80         /** @var App */
81         protected $app;
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(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 = [])
100         {
101                 parent::__construct($mode, $session, $database, $pConfig, $config, $cache, $l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
102
103                 $this->app            = $app;
104                 $this->timeline       = $timeline;
105                 $this->systemMessages = $systemMessages;
106                 $this->conversation   = $conversation;
107                 $this->page           = $page;
108         }
109
110         protected function content(array $request = []): string
111         {
112                 if (!$this->session->getLocalUserId()) {
113                         return Login::form();
114                 }
115
116                 $this->parseRequest($request);
117
118                 $module = 'network';
119
120                 $this->page['aside'] .= Widget::channels($module, $this->selectedTab, $this->session->getLocalUserId());
121                 $this->page['aside'] .= Widget::accountTypes($module, $this->accountTypeString);
122
123                 $arr = ['query' => $this->args->getQueryString()];
124                 Hook::callAll('network_content_init', $arr);
125
126                 $o = '';
127
128                 if ($this->timeline->isChannel($this->selectedTab)) {
129                         if (!in_array($this->selectedTab, [TimelineEntity::FOLLOWERS, TimelineEntity::FORYOU]) && $this->config->get('system', 'community_no_sharer')) {
130                                 $this->page['aside'] .= $this->getNoSharerWidget($module);
131                         }
132
133                         $items = $this->getChannelItems();
134                 } elseif ($this->timeline->isCommunity($this->selectedTab)) {
135                         if ($this->session->getLocalUserId() && $this->config->get('system', 'community_no_sharer')) {
136                                 $this->page['aside'] .= $this->getNoSharerWidget($module);
137                         }
138
139                         $items = $this->getCommunityItems();
140                 } else {
141                         $items = $this->getItems();
142                 }
143
144                 $this->page['aside'] .= Circle::sidebarWidget($module, $module . '/circle', 'standard', $this->circleId);
145                 $this->page['aside'] .= GroupManager::widget($module . '/group', $this->session->getLocalUserId(), $this->groupContactId);
146                 $this->page['aside'] .= Widget::postedByYear($module . '/archive', $this->session->getLocalUserId(), false);
147                 $this->page['aside'] .= Widget::networks($module, !$this->groupContactId ? $this->network : '');
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                 $o .= $this->conversation->render($items, Conversation::MODE_NETWORK, false, false, $this->getOrder(), $this->session->getLocalUserId());
240
241                 if ($this->pConfig->get($this->session->getLocalUserId(), 'system', 'infinite_scroll')) {
242                         $o .= HTML::scrollLoader();
243                 } else {
244                         $pager = new BoundariesPager(
245                                 $this->l10n,
246                                 $this->args->getQueryString(),
247                                 $items[0][$this->order] ?? null,
248                                 $items[count($items) - 1][$this->order] ?? null,
249                                 $this->itemsPerPage
250                         );
251
252                         $o .= $pager->renderMinimal(count($items));
253                 }
254
255                 return $o;
256         }
257
258         protected function getOrder(): string
259         {
260                 if ($this->order === 'received') {
261                         return '`received`';
262                 } elseif ($this->order === 'created') {
263                         return '`created`';
264                 } else {
265                         return '`commented`';
266                 }
267         }
268
269         /**
270          * Get the network tabs menu
271          *
272          * @return string Html of the network tabs
273          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
274          */
275         private function getTabsHTML()
276         {
277                 // @todo user confgurable selection of tabs
278                 $tabs = $this->getTabArray($this->timeline->getNetworkFeeds($this->args->getCommand()), 'network');
279
280                 $network_timelines = $this->pConfig->get($this->session->getLocalUserId(), 'system', 'network_timelines', []);
281                 if (!empty($network_timelines)) {
282                         $tabs = array_merge($tabs, $this->getTabArray($this->timeline->getChannelsForUser($this->session->getLocalUserId()), 'network', 'channel'));
283                         $tabs = array_merge($tabs, $this->getTabArray($this->timeline->getCommunities(true), 'network', 'channel'));
284                 }
285
286                 $arr = ['tabs' => $tabs];
287                 Hook::callAll('network_tabs', $arr);
288
289                 if (!empty($network_timelines)) {
290                         $tabs = [];
291
292                         foreach (array_keys($arr['tabs']) as $tab) {
293                                 if (in_array($tab, $network_timelines)) {
294                                         $tabs[] = $arr['tabs'][$tab];
295                                 }
296                         }
297                 } else {
298                         $tabs = $arr['tabs'];
299                 }
300
301                 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
302
303                 return Renderer::replaceMacros($tpl, ['$tabs' => $tabs]);
304         }
305
306         protected function parseRequest(array $request)
307         {
308                 parent::parseRequest($request);
309
310                 $this->circleId = (int)($this->parameters['circle_id'] ?? 0);
311
312                 $this->groupContactId = (int)($this->parameters['contact_id'] ?? 0);
313
314                 if (!$this->selectedTab) {
315                         $this->selectedTab = self::getTimelineOrderBySession($this->session, $this->pConfig);
316                 } elseif (!$this->timeline->isChannel($this->selectedTab) && !$this->timeline->isCommunity($this->selectedTab)) {
317                         throw new HTTPException\BadRequestException($this->l10n->t('Network feed not available.'));
318                 }
319
320                 if (($this->network || $this->circleId || $this->groupContactId) && ($this->timeline->isChannel($this->selectedTab) || $this->timeline->isCommunity($this->selectedTab))) {
321                         $this->selectedTab = TimelineEntity::RECEIVED;
322                 }
323
324                 if (!empty($request['star'])) {
325                         $this->selectedTab = TimelineEntity::STAR;
326                         $this->star = true;
327                 } else {
328                         $this->star = $this->selectedTab == TimelineEntity::STAR;
329                 }
330
331                 if (!empty($request['mention'])) {
332                         $this->selectedTab = TimelineEntity::MENTION;
333                         $this->mention = true;
334                 } else {
335                         $this->mention = $this->selectedTab == TimelineEntity::MENTION;
336                 }
337
338                 if (!empty($request['order'])) {
339                         $this->selectedTab = $request['order'];
340                         $this->order = $request['order'];
341                         $this->star = false;
342                         $this->mention = false;
343                 } elseif (in_array($this->selectedTab, [TimelineEntity::RECEIVED, TimelineEntity::STAR]) || $this->timeline->isCommunity($this->selectedTab)) {
344                         $this->order = 'received';
345                 } elseif (($this->selectedTab == TimelineEntity::CREATED) || $this->timeline->isChannel($this->selectedTab)) {
346                         $this->order = 'created';
347                 } else {
348                         $this->order = 'commented';
349                 }
350
351                 // Upon updates in the background and order by last comment we order by received date,
352                 // since otherwise the feed will optically jump, when some already visible thread has been updated.
353                 if ($this->update && ($this->selectedTab == TimelineEntity::COMMENTED)) {
354                         $this->order = 'received';
355                 }
356
357                 $this->selectedTab = $this->selectedTab ?? $this->order;
358
359                 // Prohibit combined usage of "star" and "mention"
360                 if ($this->selectedTab == TimelineEntity::STAR) {
361                         $this->mention = false;
362                 } elseif ($this->selectedTab == TimelineEntity::MENTION) {
363                         $this->star = false;
364                 }
365
366                 $this->session->set('network-tab', $this->selectedTab);
367                 $this->pConfig->set($this->session->getLocalUserId(), 'network.view', 'selected_tab', $this->selectedTab);
368
369                 $this->network = $request['nets'] ?? '';
370
371                 $this->dateFrom = $this->parameters['from'] ?? '';
372                 $this->dateTo = $this->parameters['to'] ?? '';
373
374                 switch ($this->order) {
375                         case 'received':
376                                 $this->maxId = $request['last_received'] ?? $this->maxId;
377                                 $this->minId = $request['first_received'] ?? $this->minId;
378                                 break;
379                         case 'created':
380                                 $this->maxId = $request['last_created'] ?? $this->maxId;
381                                 $this->minId = $request['first_created'] ?? $this->minId;
382                                 break;
383                         case 'uriid':
384                                 $this->maxId = $request['last_uriid'] ?? $this->maxId;
385                                 $this->minId = $request['first_uriid'] ?? $this->minId;
386                                 break;
387                         default:
388                                 $this->order = 'commented';
389                                 $this->maxId = $request['last_commented'] ?? $this->maxId;
390                                 $this->minId = $request['first_commented'] ?? $this->minId;
391                 }
392         }
393
394         protected function getItems()
395         {
396                 $conditionFields  = ['uid' => $this->session->getLocalUserId()];
397                 $conditionStrings = [];
398
399                 if (!is_null($this->accountType)) {
400                         $conditionFields['contact-type'] = $this->accountType;
401                 }
402
403                 if ($this->star) {
404                         $conditionFields['starred'] = true;
405                 }
406                 if ($this->mention) {
407                         $conditionFields['mention'] = true;
408                 }
409                 if ($this->network) {
410                         $conditionFields['network'] = $this->network;
411                 }
412
413                 if ($this->dateFrom) {
414                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` <= ? ", DateTimeFormat::convert($this->dateFrom, 'UTC', $this->app->getTimeZone())]);
415                 }
416                 if ($this->dateTo) {
417                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` >= ? ", DateTimeFormat::convert($this->dateTo, 'UTC', $this->app->getTimeZone())]);
418                 }
419
420                 if ($this->circleId) {
421                         $conditionStrings = DBA::mergeConditions($conditionStrings, ["`contact-id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)", $this->circleId]);
422                 } elseif ($this->groupContactId) {
423                         $conditionStrings = DBA::mergeConditions($conditionStrings,
424                                 ["((`contact-id` = ?) OR `uri-id` IN (SELECT `parent-uri-id` FROM `post-user-view` WHERE (`contact-id` = ? AND `gravity` = ? AND `vid` = ? AND `uid` = ?)))",
425                                 $this->groupContactId, $this->groupContactId, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), $this->session->getLocalUserId()]);
426                 }
427
428                 // Currently only the order modes "received" and "commented" are in use
429                 if (!empty($this->itemUriId)) {
430                         $conditionStrings = DBA::mergeConditions($conditionStrings, ['uri-id' => $this->itemUriId]);
431                 } else {
432                         if (isset($this->maxId)) {
433                                 switch ($this->order) {
434                                         case 'received':
435                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` < ?", $this->maxId]);
436                                                 break;
437                                         case 'commented':
438                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` < ?", $this->maxId]);
439                                                 break;
440                                         case 'created':
441                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` < ?", $this->maxId]);
442                                                 break;
443                                         case 'uriid':
444                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` < ?", $this->maxId]);
445                                                 break;
446                                 }
447                         }
448
449                         if (isset($this->minId)) {
450                                 switch ($this->order) {
451                                         case 'received':
452                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`received` > ?", $this->minId]);
453                                                 break;
454                                         case 'commented':
455                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`commented` > ?", $this->minId]);
456                                                 break;
457                                         case 'created':
458                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`created` > ?", $this->minId]);
459                                                 break;
460                                         case 'uriid':
461                                                 $conditionStrings = DBA::mergeConditions($conditionStrings, ["`uri-id` > ?", $this->minId]);
462                                                 break;
463                                 }
464                         }
465                 }
466
467                 $params = ['limit' => $this->itemsPerPage];
468
469                 if (isset($this->minId) && !isset($this->maxId)) {
470                         // min_id quirk: querying in reverse order with min_id gets the most recent rows, regardless of how close
471                         // they are to min_id. We change the query ordering to get the expected data, and we need to reverse the
472                         // order of the results.
473                         $params['order'] = [$this->order => false];
474                 } else {
475                         $params['order'] = [$this->order => true];
476                 }
477
478                 $items = $this->database->selectToArray('network-thread-view', [], DBA::mergeConditions($conditionFields, $conditionStrings), $params);
479
480                 // min_id quirk, continued
481                 if (isset($this->minId) && !isset($this->maxId)) {
482                         $items = array_reverse($items);
483                 }
484
485                 if ($this->database->isResult($items)) {
486                         $parents = array_column($items, 'uri-id');
487                 } else {
488                         $parents = [];
489                 }
490
491                 // We aren't going to try and figure out at the item, circle, and page
492                 // level which items you've seen and which you haven't. If you're looking
493                 // at the top level network page just mark everything seen.
494                 if (!$this->circleId && !$this->groupContactId && !$this->star && !$this->mention) {
495                         $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId()];
496                         $this->setItemsSeenByCondition($condition);
497                 } elseif (!empty($parents)) {
498                         $condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => $parents];
499                         $this->setItemsSeenByCondition($condition);
500                 }
501
502                 return $items;
503         }
504
505         /**
506          * Returns the selected network tab of the currently logged-in user
507          *
508          * @param IHandleUserSessions         $session
509          * @param IManagePersonalConfigValues $pconfig
510          * @return string
511          */
512         public static function getTimelineOrderBySession(IHandleUserSessions $session, IManagePersonalConfigValues $pconfig): string
513         {
514                 return $session->get('network-tab')
515                         ?? $pconfig->get($session->getLocalUserId(), 'network.view', 'selected_tab')
516                         ?? '';
517         }
518 }