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