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