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