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