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