]> git.mxchange.org Git - friendica.git/blob - mod/network.php
Move L10n::tt() calls to DI::l10n()->tt() calls
[friendica.git] / mod / network.php
1 <?php
2
3 /**
4  * @file mod/network.php
5  */
6
7 use Friendica\App;
8 use Friendica\Content\Feature;
9 use Friendica\Content\ForumManager;
10 use Friendica\Content\Nav;
11 use Friendica\Content\Pager;
12 use Friendica\Content\Widget;
13 use Friendica\Content\Text\HTML;
14 use Friendica\Core\ACL;
15 use Friendica\Core\Config;
16 use Friendica\Core\Hook;
17 use Friendica\Core\L10n;
18 use Friendica\Core\Logger;
19 use Friendica\Core\Protocol;
20 use Friendica\Core\Renderer;
21 use Friendica\Core\Session;
22 use Friendica\Database\DBA;
23 use Friendica\DI;
24 use Friendica\Model\Contact;
25 use Friendica\Model\Group;
26 use Friendica\Model\Item;
27 use Friendica\Model\Profile;
28 use Friendica\Model\Term;
29 use Friendica\Module\Security\Login;
30 use Friendica\Util\DateTimeFormat;
31 use Friendica\Util\Proxy as ProxyUtils;
32 use Friendica\Util\Strings;
33
34 function network_init(App $a)
35 {
36         if (!local_user()) {
37                 notice(DI::l10n()->t('Permission denied.') . EOL);
38                 return;
39         }
40
41         Hook::add('head', __FILE__, 'network_infinite_scroll_head');
42
43         $is_a_date_query = false;
44
45         $group_id = (($a->argc > 1 && is_numeric($a->argv[1])) ? intval($a->argv[1]) : 0);
46
47         $cid = 0;
48         if (!empty($_GET['cid'])) {
49                 $cid = $_GET['cid'];
50                 $_GET['nets'] = '';
51                 $group_id = 0;
52         }
53
54         if ($a->argc > 1) {
55                 for ($x = 1; $x < $a->argc; $x ++) {
56                         if (DI::dtFormat()->isYearMonthDay($a->argv[$x])) {
57                                 $is_a_date_query = true;
58                                 break;
59                         }
60                 }
61         }
62
63         // convert query string to array. remove friendica args
64         $query_array = [];
65         parse_str(parse_url(DI::args()->getQueryString(), PHP_URL_QUERY), $query_array);
66
67         // fetch last used network view and redirect if needed
68         if (!$is_a_date_query) {
69                 $sel_nets = $_GET['nets'] ?? '';
70                 $sel_tabs = network_query_get_sel_tab($a);
71                 $sel_groups = network_query_get_sel_group($a);
72                 $last_sel_tabs = DI::pConfig()->get(local_user(), 'network.view', 'tab.selected');
73
74                 $remember_tab = ($sel_tabs[0] === 'active' && is_array($last_sel_tabs) && $last_sel_tabs[0] !== 'active');
75
76                 $net_baseurl = '/network';
77                 $net_args = [];
78
79                 if ($sel_groups !== false) {
80                         $net_baseurl .= '/' . $sel_groups;
81                 }
82
83                 if ($remember_tab) {
84                         // redirect if current selected tab is '/network' and
85                         // last selected tab is _not_ '/network?order=activity'.
86                         // and this isn't a date query
87
88                         $tab_args = [
89                                 'order=activity', //all
90                                 'order=post',     //postord
91                                 'conv=1',         //conv
92                                 'new=1',          //new
93                                 'star=1',         //starred
94                                 'bmark=1',        //bookmarked
95                         ];
96
97                         $k = array_search('active', $last_sel_tabs);
98
99                         if ($k != 3) {
100                                 // parse out tab queries
101                                 $dest_qa = [];
102                                 $dest_qs = $tab_args[$k];
103                                 parse_str($dest_qs, $dest_qa);
104                                 $net_args = array_merge($net_args, $dest_qa);
105                         } else {
106                                 $remember_tab = false;
107                         }
108                 }
109
110                 if ($sel_nets) {
111                         $net_args['nets'] = $sel_nets;
112                 }
113
114                 if ($remember_tab) {
115                         $net_args = array_merge($query_array, $net_args);
116                         $net_queries = http_build_query($net_args);
117
118                         $redir_url = ($net_queries ? $net_baseurl . '?' . $net_queries : $net_baseurl);
119
120                         DI::baseUrl()->redirect($redir_url);
121                 }
122         }
123
124         if (empty(DI::page()['aside'])) {
125                 DI::page()['aside'] = '';
126         }
127
128         DI::page()['aside'] .= Group::sidebarWidget('network/0', 'network', 'standard', $group_id);
129         DI::page()['aside'] .= ForumManager::widget(local_user(), $cid);
130         DI::page()['aside'] .= Widget::postedByYear('network', local_user(), false);
131         DI::page()['aside'] .= Widget::networks('network', $_GET['nets'] ?? '');
132         DI::page()['aside'] .= Widget\SavedSearches::getHTML(DI::args()->getQueryString());
133         DI::page()['aside'] .= Widget::fileAs('network', $_GET['file'] ?? '');
134 }
135
136 /**
137  * Return selected tab from query
138  *
139  * urls -> returns
140  *        '/network'                => $no_active = 'active'
141  *        '/network?order=activity' => $activity_active = 'active'
142  *        '/network?order=post'     => $postord_active = 'active'
143  *        '/network?conv=1',        => $conv_active = 'active'
144  *        '/network?new=1',         => $new_active = 'active'
145  *        '/network?star=1',        => $starred_active = 'active'
146  *        '/network?bmark=1',       => $bookmarked_active = 'active'
147  *
148  * @param App $a
149  * @return array ($no_active, $activity_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active);
150  */
151 function network_query_get_sel_tab(App $a)
152 {
153         $no_active = '';
154         $starred_active = '';
155         $new_active = '';
156         $bookmarked_active = '';
157         $all_active = '';
158         $conv_active = '';
159         $postord_active = '';
160
161         if (!empty($_GET['new'])) {
162                 $new_active = 'active';
163         }
164
165         if (!empty($_GET['star'])) {
166                 $starred_active = 'active';
167         }
168
169         if (!empty($_GET['bmark'])) {
170                 $bookmarked_active = 'active';
171         }
172
173         if (!empty($_GET['conv'])) {
174                 $conv_active = 'active';
175         }
176
177         if (($new_active == '') && ($starred_active == '') && ($bookmarked_active == '') && ($conv_active == '')) {
178                 $no_active = 'active';
179         }
180
181         if ($no_active == 'active' && !empty($_GET['order'])) {
182                 switch($_GET['order']) {
183                         case 'post' :     $postord_active = 'active'; $no_active=''; break;
184                         case 'activity' : $all_active     = 'active'; $no_active=''; break;
185                 }
186         }
187
188         return [$no_active, $all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active];
189 }
190
191 function network_query_get_sel_group(App $a)
192 {
193         $group = false;
194
195         if ($a->argc >= 2 && is_numeric($a->argv[1])) {
196                 $group = $a->argv[1];
197         }
198
199         return $group;
200 }
201
202 /**
203  * Sets the pager data and returns SQL
204  *
205  * @param App     $a      The global App
206  * @param Pager   $pager
207  * @param integer $update Used for the automatic reloading
208  * @return string SQL with the appropriate LIMIT clause
209  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
210  */
211 function networkPager(App $a, Pager $pager, $update)
212 {
213         if ($update) {
214                 // only setup pagination on initial page view
215                 return ' LIMIT 100';
216         }
217
218         //  check if we serve a mobile device and get the user settings
219         //  accordingly
220         if (DI::mode()->isMobile()) {
221                 $itemspage_network = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network');
222                 $itemspage_network = ((intval($itemspage_network)) ? $itemspage_network : 20);
223         } else {
224                 $itemspage_network = DI::pConfig()->get(local_user(), 'system', 'itemspage_network');
225                 $itemspage_network = ((intval($itemspage_network)) ? $itemspage_network : 40);
226         }
227
228         //  now that we have the user settings, see if the theme forces
229         //  a maximum item number which is lower then the user choice
230         if (($a->force_max_items > 0) && ($a->force_max_items < $itemspage_network)) {
231                 $itemspage_network = $a->force_max_items;
232         }
233
234         $pager->setItemsPerPage($itemspage_network);
235
236         return sprintf(" LIMIT %d, %d ", $pager->getStart(), $pager->getItemsPerPage());
237 }
238
239 /**
240  * Sets items as seen
241  *
242  * @param array $condition The array with the SQL condition
243  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
244  */
245 function networkSetSeen($condition)
246 {
247         if (empty($condition)) {
248                 return;
249         }
250
251         $unseen = Item::exists($condition);
252
253         if ($unseen) {
254                 Item::update(['unseen' => false], $condition);
255         }
256 }
257
258 /**
259  * Create the conversation HTML
260  *
261  * @param App     $a      The global App
262  * @param array   $items  Items of the conversation
263  * @param Pager   $pager
264  * @param string  $mode   Display mode for the conversation
265  * @param integer $update Used for the automatic reloading
266  * @param string  $ordering
267  * @return string HTML of the conversation
268  * @throws ImagickException
269  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
270  */
271 function networkConversation(App $a, $items, Pager $pager, $mode, $update, $ordering = '')
272 {
273         // Set this so that the conversation function can find out contact info for our wall-wall items
274         $a->page_contact = $a->contact;
275
276         if (!is_array($items)) {
277                 Logger::log("Expecting items to be an array. Got " . print_r($items, true));
278                 $items = [];
279         }
280
281         $o = conversation($a, $items, $pager, $mode, $update, false, $ordering, local_user());
282
283         if (!$update) {
284                 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
285                         $o .= HTML::scrollLoader();
286                 } else {
287                         $o .= $pager->renderMinimal(count($items));
288                 }
289         }
290
291         return $o;
292 }
293
294 function network_content(App $a, $update = 0, $parent = 0)
295 {
296         if (!local_user()) {
297                 return Login::form();
298         }
299
300         /// @TODO Is this really necessary? $a is already available to hooks
301         $arr = ['query' => DI::args()->getQueryString()];
302         Hook::callAll('network_content_init', $arr);
303
304         if (!empty($_GET['new']) || !empty($_GET['file'])) {
305                 $o = networkFlatView($a, $update);
306         } else {
307                 $o = networkThreadedView($a, $update, $parent);
308         }
309
310         if ($o === '') {
311                 info("No items found");
312         }
313
314         return $o;
315 }
316
317 /**
318  * Get the network content in flat view
319  *
320  * @param App     $a      The global App
321  * @param integer $update Used for the automatic reloading
322  * @return string HTML of the network content in flat view
323  * @throws ImagickException
324  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
325  * @global Pager  $pager
326  */
327 function networkFlatView(App $a, $update = 0)
328 {
329         global $pager;
330         // Rawmode is used for fetching new content at the end of the page
331         $rawmode = (isset($_GET['mode']) && ($_GET['mode'] == 'raw'));
332
333         $o = '';
334
335         $file = $_GET['file'] ?? '';
336
337         if (!$update && !$rawmode) {
338                 $tabs = network_tabs($a);
339                 $o .= $tabs;
340
341                 Nav::setSelected('network');
342
343                 $x = [
344                         'is_owner' => true,
345                         'allow_location' => $a->user['allow_location'],
346                         'default_location' => $a->user['default-location'],
347                         'nickname' => $a->user['nickname'],
348                         'lockstate' => (is_array($a->user) &&
349                         (strlen($a->user['allow_cid']) || strlen($a->user['allow_gid']) ||
350                         strlen($a->user['deny_cid']) || strlen($a->user['deny_gid'])) ? 'lock' : 'unlock'),
351                         'default_perms' => ACL::getDefaultUserPermissions($a->user),
352                         'acl' => ACL::getFullSelectorHTML(DI::page(), $a->user, true),
353                         'bang' => '',
354                         'visitor' => 'block',
355                         'profile_uid' => local_user(),
356                         'content' => '',
357                 ];
358
359                 $o .= status_editor($a, $x);
360
361                 if (!Config::get('theme', 'hide_eventlist')) {
362                         $o .= Profile::getBirthdays();
363                         $o .= Profile::getEventsReminderHTML();
364                 }
365         }
366
367         $pager = new Pager(DI::args()->getQueryString());
368
369         networkPager($a, $pager, $update);
370
371         $item_params = ['order' => ['id' => true]];
372
373         if (strlen($file)) {
374                 $term_condition = ["`term` = ? AND `otype` = ? AND `type` = ? AND `uid` = ?",
375                         $file, Term::OBJECT_TYPE_POST, Term::FILE, local_user()];
376                 $term_params = ['order' => ['tid' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
377                 $result = DBA::select('term', ['oid'], $term_condition, $term_params);
378
379                 $posts = [];
380                 while ($term = DBA::fetch($result)) {
381                         $posts[] = $term['oid'];
382                 }
383                 DBA::close($result);
384
385                 if (count($posts) == 0) {
386                         return '';
387                 }
388                 $item_condition = ['uid' => local_user(), 'id' => $posts];
389         } else {
390                 $item_condition = ['uid' => local_user()];
391                 $item_params['limit'] = [$pager->getStart(), $pager->getItemsPerPage()];
392
393                 networkSetSeen(['unseen' => true, 'uid' => local_user()]);
394         }
395
396         $result = Item::selectForUser(local_user(), [], $item_condition, $item_params);
397         $items = Item::inArray($result);
398         $o .= networkConversation($a, $items, $pager, 'network-new', $update);
399
400         return $o;
401 }
402
403 /**
404  * Get the network content in threaded view
405  *
406  * @param  App     $a      The global App
407  * @param  integer $update Used for the automatic reloading
408  * @param  integer $parent
409  * @return string HTML of the network content in flat view
410  * @throws ImagickException
411  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
412  * @global Pager   $pager
413  */
414 function networkThreadedView(App $a, $update, $parent)
415 {
416         /// @TODO this will have to be converted to a static property of the converted Module\Network class
417         global $pager;
418
419         // Rawmode is used for fetching new content at the end of the page
420         $rawmode = (isset($_GET['mode']) AND ( $_GET['mode'] == 'raw'));
421
422         if (isset($_GET['last_received']) && isset($_GET['last_commented']) && isset($_GET['last_created']) && isset($_GET['last_id'])) {
423                 $last_received = DateTimeFormat::utc($_GET['last_received']);
424                 $last_commented = DateTimeFormat::utc($_GET['last_commented']);
425                 $last_created = DateTimeFormat::utc($_GET['last_created']);
426                 $last_id = intval($_GET['last_id']);
427         } else {
428                 $last_received = '';
429                 $last_commented = '';
430                 $last_created = '';
431                 $last_id = 0;
432         }
433
434         $datequery = $datequery2 = '';
435
436         $gid = 0;
437
438         $default_permissions = [];
439
440         if ($a->argc > 1) {
441                 for ($x = 1; $x < $a->argc; $x ++) {
442                         if (DI::dtFormat()->isYearMonthDay($a->argv[$x])) {
443                                 if ($datequery) {
444                                         $datequery2 = Strings::escapeHtml($a->argv[$x]);
445                                 } else {
446                                         $datequery = Strings::escapeHtml($a->argv[$x]);
447                                         $_GET['order'] = 'post';
448                                 }
449                         } elseif (intval($a->argv[$x])) {
450                                 $gid = intval($a->argv[$x]);
451                                 $default_permissions['allow_gid'] = [$gid];
452                         }
453                 }
454         }
455
456         $o = '';
457
458         $cid   = intval($_GET['cid']   ?? 0);
459         $star  = intval($_GET['star']  ?? 0);
460         $bmark = intval($_GET['bmark'] ?? 0);
461         $conv  = intval($_GET['conv']  ?? 0);
462         $order = Strings::escapeTags(($_GET['order'] ?? '') ?: 'activity');
463         $nets  =        $_GET['nets']  ?? '';
464
465         $allowedCids = [];
466         if ($cid) {
467                 $allowedCids[] = (int) $cid;
468         } elseif ($nets) {
469                 $condition = [
470                         'uid'     => local_user(),
471                         'network' => $nets,
472                         'self'    => false,
473                         'blocked' => false,
474                         'pending' => false,
475                         'archive' => false,
476                         'rel'     => [Contact::SHARING, Contact::FRIEND],
477                 ];
478                 $contactStmt = DBA::select('contact', ['id'], $condition);
479                 while ($contact = DBA::fetch($contactStmt)) {
480                         $allowedCids[] = (int) $contact['id'];
481                 }
482                 DBA::close($contactStmt);
483         }
484
485         if (count($allowedCids)) {
486                 $default_permissions['allow_cid'] = $allowedCids;
487         }
488
489         if (!$update && !$rawmode) {
490                 $tabs = network_tabs($a);
491                 $o .= $tabs;
492
493                 if ($gid && ($t = Contact::getOStatusCountByGroupId($gid)) && !DI::pConfig()->get(local_user(), 'system', 'nowarn_insecure')) {
494                         notice(DI::l10n()->tt("Warning: This group contains %s member from a network that doesn't allow non public messages.",
495                                 "Warning: This group contains %s members from a network that doesn't allow non public messages.",
496                                 $t) . EOL);
497                         notice(DI::l10n()->t("Messages in this group won't be send to these receivers.").EOL);
498                 }
499
500                 Nav::setSelected('network');
501
502                 $content = '';
503
504                 if ($cid) {
505                         // If $cid belongs to a communitity forum or a privat goup,.add a mention to the status editor
506                         $condition = ["`id` = ? AND (`forum` OR `prv`)", $cid];
507                         $contact = DBA::selectFirst('contact', ['addr', 'nick'], $condition);
508                         if (DBA::isResult($contact)) {
509                                 if ($contact['addr'] != '') {
510                                         $content = '!' . $contact['addr'];
511                                 } else {
512                                         $content = '!' . $contact['nick'] . '+' . $cid;
513                                 }
514                         }
515                 }
516
517                 $x = [
518                         'is_owner' => true,
519                         'allow_location' => $a->user['allow_location'],
520                         'default_location' => $a->user['default-location'],
521                         'nickname' => $a->user['nickname'],
522                         'lockstate' => ($gid || $cid || $nets || (is_array($a->user) &&
523                         (strlen($a->user['allow_cid']) || strlen($a->user['allow_gid']) ||
524                         strlen($a->user['deny_cid']) || strlen($a->user['deny_gid']))) ? 'lock' : 'unlock'),
525                         'default_perms' => ACL::getDefaultUserPermissions($a->user),
526                         'acl' => ACL::getFullSelectorHTML(DI::page(), $a->user, true, $default_permissions),
527                         'bang' => (($gid || $cid || $nets) ? '!' : ''),
528                         'visitor' => 'block',
529                         'profile_uid' => local_user(),
530                         'content' => $content,
531                 ];
532
533                 $o .= status_editor($a, $x);
534         }
535
536         // We don't have to deal with ACLs on this page. You're looking at everything
537         // that belongs to you, hence you can see all of it. We will filter by group if
538         // desired.
539
540         $sql_post_table = '';
541         $sql_options = ($star ? " AND `thread`.`starred` " : '');
542         $sql_options .= ($bmark ? sprintf(" AND `thread`.`post-type` = %d ", Item::PT_PAGE) : '');
543         $sql_extra = $sql_options;
544         $sql_extra2 = '';
545         $sql_extra3 = '';
546         $sql_table = '`thread`';
547         $sql_parent = '`iid`';
548
549         if ($update) {
550                 $sql_table = '`item`';
551                 $sql_parent = '`parent`';
552                 $sql_post_table = " INNER JOIN `thread` ON `thread`.`iid` = `item`.`parent`";
553         }
554
555         $sql_nets = (($nets) ? sprintf(" AND $sql_table.`network` = '%s' ", DBA::escape($nets)) : '');
556         $sql_tag_nets = (($nets) ? sprintf(" AND `item`.`network` = '%s' ", DBA::escape($nets)) : '');
557
558         if ($gid) {
559                 $group = DBA::selectFirst('group', ['name'], ['id' => $gid, 'uid' => local_user()]);
560                 if (!DBA::isResult($group)) {
561                         if ($update) {
562                                 exit();
563                         }
564                         notice(DI::l10n()->t('No such group') . EOL);
565                         DI::baseUrl()->redirect('network/0');
566                         // NOTREACHED
567                 }
568
569                 $contacts = Group::expand(local_user(), [$gid]);
570
571                 if ((is_array($contacts)) && count($contacts)) {
572                         $contact_str_self = '';
573
574                         $contact_str = implode(',', $contacts);
575                         $self = DBA::selectFirst('contact', ['id'], ['uid' => local_user(), 'self' => true]);
576                         if (DBA::isResult($self)) {
577                                 $contact_str_self = $self['id'];
578                         }
579
580                         $sql_post_table .= " INNER JOIN `item` AS `temp1` ON `temp1`.`id` = " . $sql_table . "." . $sql_parent;
581                         $sql_extra3 .= " AND (`thread`.`contact-id` IN ($contact_str) ";
582                         $sql_extra3 .= " OR (`thread`.`contact-id` = '$contact_str_self' AND `temp1`.`allow_gid` LIKE '" . Strings::protectSprintf('%<' . intval($gid) . '>%') . "' AND `temp1`.`private`))";
583                 } else {
584                         $sql_extra3 .= " AND false ";
585                         info(DI::l10n()->t('Group is empty'));
586                 }
587
588                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
589                         '$title' => DI::l10n()->t('Group: %s', $group['name'])
590                 ]) . $o;
591         } elseif ($cid) {
592                 $fields = ['id', 'name', 'network', 'writable', 'nurl',
593                         'forum', 'prv', 'contact-type', 'addr', 'thumb', 'location'];
594                 $condition = ["`id` = ? AND (NOT `blocked` OR `pending`)", $cid];
595                 $contact = DBA::selectFirst('contact', $fields, $condition);
596                 if (DBA::isResult($contact)) {
597                         $sql_extra = " AND " . $sql_table . ".`contact-id` = " . intval($cid);
598
599                         $entries[0] = [
600                                 'id' => 'network',
601                                 'name' => $contact['name'],
602                                 'itemurl' => ($contact['addr'] ?? '') ?: $contact['nurl'],
603                                 'thumb' => ProxyUtils::proxifyUrl($contact['thumb'], false, ProxyUtils::SIZE_THUMB),
604                                 'details' => $contact['location'],
605                         ];
606
607                         $entries[0]['account_type'] = Contact::getAccountType($contact);
608
609                         $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('viewcontact_template.tpl'), [
610                                 'contacts' => $entries,
611                                 'id' => 'network',
612                         ]) . $o;
613
614                         if ($contact['network'] === Protocol::OSTATUS && $contact['writable'] && !DI::pConfig()->get(local_user(),'system','nowarn_insecure')) {
615                                 notice(DI::l10n()->t('Private messages to this person are at risk of public disclosure.') . EOL);
616                         }
617                 } else {
618                         notice(DI::l10n()->t('Invalid contact.') . EOL);
619                         DI::baseUrl()->redirect('network');
620                         // NOTREACHED
621                 }
622         }
623
624         if (!$gid && !$cid && !$update && !Config::get('theme', 'hide_eventlist')) {
625                 $o .= Profile::getBirthdays();
626                 $o .= Profile::getEventsReminderHTML();
627         }
628
629         if ($datequery) {
630                 $sql_extra3 .= Strings::protectSprintf(sprintf(" AND $sql_table.received <= '%s' ",
631                                 DBA::escape(DateTimeFormat::convert($datequery, 'UTC', date_default_timezone_get()))));
632         }
633         if ($datequery2) {
634                 $sql_extra3 .= Strings::protectSprintf(sprintf(" AND $sql_table.received >= '%s' ",
635                                 DBA::escape(DateTimeFormat::convert($datequery2, 'UTC', date_default_timezone_get()))));
636         }
637
638         if ($conv) {
639                 $sql_extra3 .= " AND $sql_table.`mention`";
640         }
641
642         // Normal conversation view
643         if ($order === 'post') {
644                 $ordering = '`received`';
645                 $order_mode = 'received';
646         } else {
647                 $ordering = '`commented`';
648                 $order_mode = 'commented';
649         }
650
651         $sql_order = "$sql_table.$ordering";
652
653         if (!empty($_GET['offset'])) {
654                 $sql_range = sprintf(" AND $sql_order <= '%s'", DBA::escape($_GET['offset']));
655         } else {
656                 $sql_range = '';
657         }
658
659         $pager = new Pager(DI::args()->getQueryString());
660
661         $pager_sql = networkPager($a, $pager, $update);
662
663         $last_date = '';
664
665         switch ($order_mode) {
666                 case 'received':
667                         if ($last_received != '') {
668                                 $last_date = $last_received;
669                                 $sql_range .= sprintf(" AND $sql_table.`received` < '%s'", DBA::escape($last_received));
670                                 $pager->setPage(1);
671                                 $pager_sql = sprintf(" LIMIT %d, %d ", $pager->getStart(), $pager->getItemsPerPage());
672                         }
673                         break;
674                 case 'commented':
675                         if ($last_commented != '') {
676                                 $last_date = $last_commented;
677                                 $sql_range .= sprintf(" AND $sql_table.`commented` < '%s'", DBA::escape($last_commented));
678                                 $pager->setPage(1);
679                                 $pager_sql = sprintf(" LIMIT %d, %d ", $pager->getStart(), $pager->getItemsPerPage());
680                         }
681                         break;
682                 case 'created':
683                         if ($last_created != '') {
684                                 $last_date = $last_created;
685                                 $sql_range .= sprintf(" AND $sql_table.`created` < '%s'", DBA::escape($last_created));
686                                 $pager->setPage(1);
687                                 $pager_sql = sprintf(" LIMIT %d, %d ", $pager->getStart(), $pager->getItemsPerPage());
688                         }
689                         break;
690                 case 'id':
691                         if (($last_id > 0) && ($sql_table == '`thread`')) {
692                                 $sql_range .= sprintf(" AND $sql_table.`iid` < '%s'", DBA::escape($last_id));
693                                 $pager->setPage(1);
694                                 $pager_sql = sprintf(" LIMIT %d, %d ", $pager->getStart(), $pager->getItemsPerPage());
695                         }
696                         break;
697         }
698
699         // Fetch a page full of parent items for this page
700         if ($update) {
701                 if (!empty($parent)) {
702                         // Load only a single thread
703                         $sql_extra4 = "`item`.`id` = ".intval($parent);
704                 } else {
705                         // Load all unseen items
706                         $sql_extra4 = "`item`.`unseen`";
707                         if (Config::get("system", "like_no_comment")) {
708                                 $sql_extra4 .= " AND `item`.`gravity` IN (" . GRAVITY_PARENT . "," . GRAVITY_COMMENT . ")";
709                         }
710                         if ($order === 'post') {
711                                 // Only show toplevel posts when updating posts in this order mode
712                                 $sql_extra4 .= " AND `item`.`id` = `item`.`parent`";
713                         }
714                 }
715
716                 $r = q("SELECT `item`.`parent-uri` AS `uri`, `item`.`parent` AS `item_id`, $sql_order AS `order_date`
717                         FROM `item` $sql_post_table
718                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
719                                 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
720                                 AND (`item`.`gravity` != %d
721                                         OR `contact`.`uid` = `item`.`uid` AND `contact`.`self`
722                                         OR `contact`.`rel` IN (%d, %d) AND NOT `contact`.`readonly`)
723                         LEFT JOIN `user-item` ON `user-item`.`iid` = `item`.`id` AND `user-item`.`uid` = %d
724                         WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`deleted`
725                         AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
726                         AND NOT `item`.`moderated` AND $sql_extra4
727                         $sql_extra3 $sql_extra $sql_range $sql_nets
728                         ORDER BY `order_date` DESC LIMIT 100",
729                         intval(GRAVITY_PARENT),
730                         intval(Contact::SHARING),
731                         intval(Contact::FRIEND),
732                         intval(local_user()),
733                         intval(local_user())
734                 );
735         } else {
736                 $r = q("SELECT `item`.`uri`, `thread`.`iid` AS `item_id`, $sql_order AS `order_date`
737                         FROM `thread` $sql_post_table
738                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `thread`.`contact-id`
739                                 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
740                         STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
741                                 AND (`item`.`gravity` != %d
742                                         OR `contact`.`uid` = `item`.`uid` AND `contact`.`self`
743                                         OR `contact`.`rel` IN (%d, %d) AND NOT `contact`.`readonly`)
744                         LEFT JOIN `user-item` ON `user-item`.`iid` = `item`.`id` AND `user-item`.`uid` = %d
745                         WHERE `thread`.`uid` = %d AND `thread`.`visible` AND NOT `thread`.`deleted`
746                         AND NOT `thread`.`moderated`
747                         AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
748                         $sql_extra2 $sql_extra3 $sql_range $sql_extra $sql_nets
749                         ORDER BY `order_date` DESC $pager_sql",
750                         intval(GRAVITY_PARENT),
751                         intval(Contact::SHARING),
752                         intval(Contact::FRIEND),
753                         intval(local_user()),
754                         intval(local_user())
755                 );
756         }
757
758         // Only show it when unfiltered (no groups, no networks, ...)
759         if (in_array($nets, ['', Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]) && (strlen($sql_extra . $sql_extra2 . $sql_extra3) == 0)) {
760                 if (DBA::isResult($r)) {
761                         $top_limit = current($r)['order_date'];
762                         $bottom_limit = end($r)['order_date'];
763                         if (empty($_SESSION['network_last_top_limit']) || ($_SESSION['network_last_top_limit'] < $top_limit)) {
764                                 $_SESSION['network_last_top_limit'] = $top_limit;
765                         }
766                 } else {
767                         $top_limit = $bottom_limit = DateTimeFormat::utcNow();
768                 }
769
770                 // When checking for updates we need to fetch from the newest date to the newest date before
771                 // Only do this, when the last stored date isn't too long ago (10 times the update interval)
772                 $browser_update = DI::pConfig()->get(local_user(), 'system', 'update_interval', 40000) / 1000;
773
774                 if (($browser_update > 0) && $update && !empty($_SESSION['network_last_date']) &&
775                         (($bottom_limit < $_SESSION['network_last_date']) || ($top_limit == $bottom_limit)) &&
776                         ((time() - $_SESSION['network_last_date_timestamp']) < ($browser_update * 10))) {
777                         $bottom_limit = $_SESSION['network_last_date'];
778                 }
779                 $_SESSION['network_last_date'] = Session::get('network_last_top_limit', $top_limit);
780                 $_SESSION['network_last_date_timestamp'] = time();
781
782                 if ($last_date > $top_limit) {
783                         $top_limit = $last_date;
784                 } elseif ($pager->getPage() == 1) {
785                         // Highest possible top limit when we are on the first page
786                         $top_limit = DateTimeFormat::utcNow();
787                 }
788
789                 $items = DBA::p("SELECT `item`.`parent-uri` AS `uri`, 0 AS `item_id`, `item`.$ordering AS `order_date`, `author`.`url` AS `author-link` FROM `item`
790                         STRAIGHT_JOIN (SELECT `oid` FROM `term` WHERE `term` IN
791                                 (SELECT SUBSTR(`term`, 2) FROM `search` WHERE `uid` = ? AND `term` LIKE '#%') AND `otype` = ? AND `type` = ? AND `uid` = 0) AS `term`
792                         ON `item`.`id` = `term`.`oid`
793                         STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = `item`.`author-id`
794                         WHERE `item`.`uid` = 0 AND `item`.$ordering < ? AND `item`.$ordering > ? AND `item`.`gravity` = ?
795                                 AND NOT `author`.`hidden` AND NOT `author`.`blocked`" . $sql_tag_nets,
796                         local_user(), TERM_OBJ_POST, TERM_HASHTAG,
797                         $top_limit, $bottom_limit, GRAVITY_PARENT);
798
799                 $data = DBA::toArray($items);
800
801                 if (count($data) > 0) {
802                         $tag_top_limit = current($data)['order_date'];
803                         if ($_SESSION['network_last_date'] < $tag_top_limit) {
804                                 $_SESSION['network_last_date'] = $tag_top_limit;
805                         }
806
807                         Logger::log('Tagged items: ' . count($data) . ' - ' . $bottom_limit . ' - ' . $top_limit . ' - ' . local_user().' - '.(int)$update);
808                         $s = [];
809                         foreach ($r as $item) {
810                                 $s[$item['uri']] = $item;
811                         }
812                         foreach ($data as $item) {
813                                 // Don't show hash tag posts from blocked or ignored contacts
814                                 $condition = ["`nurl` = ? AND `uid` = ? AND (`blocked` OR `readonly`)",
815                                         Strings::normaliseLink($item['author-link']), local_user()];
816                                 if (!DBA::exists('contact', $condition)) {
817                                         $s[$item['uri']] = $item;
818                                 }
819                         }
820                         $r = $s;
821                 }
822         }
823
824         $parents_str = '';
825         $date_offset = '';
826
827         $items = $r;
828
829         if (DBA::isResult($items)) {
830                 $parents_arr = [];
831
832                 foreach ($items as $item) {
833                         if ($date_offset < $item['order_date']) {
834                                 $date_offset = $item['order_date'];
835                         }
836                         if (!in_array($item['item_id'], $parents_arr) && ($item['item_id'] > 0)) {
837                                 $parents_arr[] = $item['item_id'];
838                         }
839                 }
840                 $parents_str = implode(', ', $parents_arr);
841         }
842
843         if (!empty($_GET['offset'])) {
844                 $date_offset = $_GET['offset'];
845         }
846
847         $query_string = DI::args()->getQueryString();
848         if ($date_offset && !preg_match('/[?&].offset=/', $query_string)) {
849                 $query_string .= '&offset=' . urlencode($date_offset);
850         }
851
852         $pager->setQueryString($query_string);
853
854         // We aren't going to try and figure out at the item, group, and page
855         // level which items you've seen and which you haven't. If you're looking
856         // at the top level network page just mark everything seen.
857
858         if (!$gid && !$cid && !$star) {
859                 $condition = ['unseen' => true, 'uid' => local_user()];
860                 networkSetSeen($condition);
861         } elseif ($parents_str) {
862                 $condition = ["`uid` = ? AND `unseen` AND `parent` IN (" . DBA::escape($parents_str) . ")", local_user()];
863                 networkSetSeen($condition);
864         }
865
866
867         $mode = 'network';
868         $o .= networkConversation($a, $items, $pager, $mode, $update, $ordering);
869
870         return $o;
871 }
872
873 /**
874  * Get the network tabs menu
875  *
876  * @param App $a The global App
877  * @return string Html of the networktab
878  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
879  */
880 function network_tabs(App $a)
881 {
882         // item filter tabs
883         /// @TODO fix this logic, reduce duplication
884         /// $a->page['content'] .= '<div class="tabs-wrapper">';
885         list($no_active, $all_active, $post_active, $conv_active, $new_active, $starred_active, $bookmarked_active) = network_query_get_sel_tab($a);
886
887         // if no tabs are selected, defaults to activitys
888         if ($no_active == 'active') {
889                 $all_active = 'active';
890         }
891
892         $cmd = DI::args()->getCommand();
893
894         $def_param = [];
895         if (!empty($_GET['cid'])) {
896                 $def_param['cid'] = $_GET['cid'];
897         }
898
899         // tabs
900         $tabs = [
901                 [
902                         'label' => DI::l10n()->t('Latest Activity'),
903                         'url'   => $cmd . '?' . http_build_query(array_merge($def_param, ['order' => 'activity'])),
904                         'sel'   => $all_active,
905                         'title' => DI::l10n()->t('Sort by latest activity'),
906                         'id'    => 'activity-order-tab',
907                         'accesskey' => 'e',
908                 ],
909                 [
910                         'label' => DI::l10n()->t('Latest Posts'),
911                         'url'   => $cmd . '?' . http_build_query(array_merge($def_param, ['order' => 'post'])),
912                         'sel'   => $post_active,
913                         'title' => DI::l10n()->t('Sort by post received date'),
914                         'id'    => 'post-order-tab',
915                         'accesskey' => 't',
916                 ],
917         ];
918
919         $tabs[] = [
920                 'label' => DI::l10n()->t('Personal'),
921                 'url'   => $cmd . '?' . http_build_query(array_merge($def_param, ['conv' => true])),
922                 'sel'   => $conv_active,
923                 'title' => DI::l10n()->t('Posts that mention or involve you'),
924                 'id'    => 'personal-tab',
925                 'accesskey' => 'r',
926         ];
927
928         if (Feature::isEnabled(local_user(), 'new_tab')) {
929                 $tabs[] = [
930                         'label' => DI::l10n()->t('New'),
931                         'url'   => $cmd . '?' . http_build_query(array_merge($def_param, ['new' => true])),
932                         'sel'   => $new_active,
933                         'title' => DI::l10n()->t('Activity Stream - by date'),
934                         'id'    => 'activitiy-by-date-tab',
935                         'accesskey' => 'w',
936                 ];
937         }
938
939         if (Feature::isEnabled(local_user(), 'link_tab')) {
940                 $tabs[] = [
941                         'label' => DI::l10n()->t('Shared Links'),
942                         'url'   => $cmd . '?' . http_build_query(array_merge($def_param, ['bmark' => true])),
943                         'sel'   => $bookmarked_active,
944                         'title' => DI::l10n()->t('Interesting Links'),
945                         'id'    => 'shared-links-tab',
946                         'accesskey' => 'b',
947                 ];
948         }
949
950         $tabs[] = [
951                 'label' => DI::l10n()->t('Starred'),
952                 'url'   => $cmd . '?' . http_build_query(array_merge($def_param, ['star' => true])),
953                 'sel'   => $starred_active,
954                 'title' => DI::l10n()->t('Favourite Posts'),
955                 'id'    => 'starred-posts-tab',
956                 'accesskey' => 'm',
957         ];
958
959         // save selected tab, but only if not in file mode
960         if (empty($_GET['file'])) {
961                 DI::pConfig()->set(local_user(), 'network.view', 'tab.selected', [
962                         $all_active, $post_active, $conv_active, $new_active, $starred_active, $bookmarked_active
963                 ]);
964         }
965
966         $arr = ['tabs' => $tabs];
967         Hook::callAll('network_tabs', $arr);
968
969         $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
970
971         return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
972
973         // --- end item filter tabs
974 }
975
976 /**
977  * Network hook into the HTML head to enable infinite scroll.
978  *
979  * Since the HTML head is built after the module content has been generated, we need to retrieve the base query string
980  * of the page to make the correct asynchronous call. This is obtained through the Pager that was instantiated in
981  * networkThreadedView or networkFlatView.
982  *
983  * @param App     $a
984  * @param  string $htmlhead The head tag HTML string
985  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
986  * @global Pager  $pager
987  */
988 function network_infinite_scroll_head(App $a, &$htmlhead)
989 {
990         /// @TODO this will have to be converted to a static property of the converted Module\Network class
991         /**
992          * @var $pager Pager
993          */
994         global $pager;
995
996         if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')
997                 && ($_GET['mode'] ?? '') != 'minimal'
998         ) {
999                 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1000                 $htmlhead .= Renderer::replaceMacros($tpl, [
1001                         '$pageno'     => $pager->getPage(),
1002                         '$reload_uri' => $pager->getBaseQueryString()
1003                 ]);
1004         }
1005 }