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