]> git.mxchange.org Git - friendica.git/blob - mod/network.php
Subscribed tags are now based on the tags as well
[friendica.git] / mod / network.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 use Friendica\App;
23 use Friendica\Content\Feature;
24 use Friendica\Content\ForumManager;
25 use Friendica\Content\Nav;
26 use Friendica\Content\Pager;
27 use Friendica\Content\Widget;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Core\ACL;
30 use Friendica\Core\Hook;
31 use Friendica\Core\Logger;
32 use Friendica\Core\Protocol;
33 use Friendica\Core\Renderer;
34 use Friendica\Core\Session;
35 use Friendica\Database\DBA;
36 use Friendica\DI;
37 use Friendica\Model\Contact;
38 use Friendica\Model\Group;
39 use Friendica\Model\Item;
40 use Friendica\Model\Profile;
41 use Friendica\Model\Tag;
42 use Friendica\Model\Term;
43 use Friendica\Module\Security\Login;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Proxy as ProxyUtils;
46 use Friendica\Util\Strings;
47
48 function network_init(App $a)
49 {
50         if (!local_user()) {
51                 notice(DI::l10n()->t('Permission denied.') . EOL);
52                 return;
53         }
54
55         Hook::add('head', __FILE__, 'network_infinite_scroll_head');
56
57         $is_a_date_query = false;
58
59         $group_id = (($a->argc > 1 && is_numeric($a->argv[1])) ? intval($a->argv[1]) : 0);
60
61         $cid = 0;
62         if (!empty($_GET['cid'])) {
63                 $cid = $_GET['cid'];
64                 $_GET['nets'] = '';
65                 $group_id = 0;
66         }
67
68         if ($a->argc > 1) {
69                 for ($x = 1; $x < $a->argc; $x ++) {
70                         if (DI::dtFormat()->isYearMonthDay($a->argv[$x])) {
71                                 $is_a_date_query = true;
72                                 break;
73                         }
74                 }
75         }
76
77         // convert query string to array. remove friendica args
78         $query_array = [];
79         parse_str(parse_url(DI::args()->getQueryString(), PHP_URL_QUERY), $query_array);
80
81         // fetch last used network view and redirect if needed
82         if (!$is_a_date_query) {
83                 $sel_nets = $_GET['nets'] ?? '';
84                 $sel_tabs = network_query_get_sel_tab($a);
85                 $sel_groups = network_query_get_sel_group($a);
86                 $last_sel_tabs = DI::pConfig()->get(local_user(), 'network.view', 'tab.selected');
87
88                 $remember_tab = ($sel_tabs[0] === 'active' && is_array($last_sel_tabs) && $last_sel_tabs[0] !== 'active');
89
90                 $net_baseurl = '/network';
91                 $net_args = [];
92
93                 if ($sel_groups !== false) {
94                         $net_baseurl .= '/' . $sel_groups;
95                 }
96
97                 if ($remember_tab) {
98                         // redirect if current selected tab is '/network' and
99                         // last selected tab is _not_ '/network?order=activity'.
100                         // and this isn't a date query
101
102                         $tab_args = [
103                                 'order=activity', //all
104                                 'order=post',     //postord
105                                 'conv=1',         //conv
106                                 'new=1',          //new
107                                 'star=1',         //starred
108                                 'bmark=1',        //bookmarked
109                         ];
110
111                         $k = array_search('active', $last_sel_tabs);
112
113                         if ($k != 3) {
114                                 // parse out tab queries
115                                 $dest_qa = [];
116                                 $dest_qs = $tab_args[$k];
117                                 parse_str($dest_qs, $dest_qa);
118                                 $net_args = array_merge($net_args, $dest_qa);
119                         } else {
120                                 $remember_tab = false;
121                         }
122                 }
123
124                 if ($sel_nets) {
125                         $net_args['nets'] = $sel_nets;
126                 }
127
128                 if ($remember_tab) {
129                         $net_args = array_merge($query_array, $net_args);
130                         $net_queries = http_build_query($net_args);
131
132                         $redir_url = ($net_queries ? $net_baseurl . '?' . $net_queries : $net_baseurl);
133
134                         DI::baseUrl()->redirect($redir_url);
135                 }
136         }
137
138         if (empty(DI::page()['aside'])) {
139                 DI::page()['aside'] = '';
140         }
141
142         DI::page()['aside'] .= Group::sidebarWidget('network/0', 'network', 'standard', $group_id);
143         DI::page()['aside'] .= ForumManager::widget(local_user(), $cid);
144         DI::page()['aside'] .= Widget::postedByYear('network', local_user(), false);
145         DI::page()['aside'] .= Widget::networks('network', $_GET['nets'] ?? '');
146         DI::page()['aside'] .= Widget\SavedSearches::getHTML(DI::args()->getQueryString());
147         DI::page()['aside'] .= Widget::fileAs('network', $_GET['file'] ?? '');
148 }
149
150 /**
151  * Return selected tab from query
152  *
153  * urls -> returns
154  *        '/network'                => $no_active = 'active'
155  *        '/network?order=activity' => $activity_active = 'active'
156  *        '/network?order=post'     => $postord_active = 'active'
157  *        '/network?conv=1',        => $conv_active = 'active'
158  *        '/network?new=1',         => $new_active = 'active'
159  *        '/network?star=1',        => $starred_active = 'active'
160  *        '/network?bmark=1',       => $bookmarked_active = 'active'
161  *
162  * @param App $a
163  * @return array ($no_active, $activity_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active);
164  */
165 function network_query_get_sel_tab(App $a)
166 {
167         $no_active = '';
168         $starred_active = '';
169         $new_active = '';
170         $bookmarked_active = '';
171         $all_active = '';
172         $conv_active = '';
173         $postord_active = '';
174
175         if (!empty($_GET['new'])) {
176                 $new_active = 'active';
177         }
178
179         if (!empty($_GET['star'])) {
180                 $starred_active = 'active';
181         }
182
183         if (!empty($_GET['bmark'])) {
184                 $bookmarked_active = 'active';
185         }
186
187         if (!empty($_GET['conv'])) {
188                 $conv_active = 'active';
189         }
190
191         if (($new_active == '') && ($starred_active == '') && ($bookmarked_active == '') && ($conv_active == '')) {
192                 $no_active = 'active';
193         }
194
195         if ($no_active == 'active' && !empty($_GET['order'])) {
196                 switch($_GET['order']) {
197                         case 'post' :     $postord_active = 'active'; $no_active=''; break;
198                         case 'activity' : $all_active     = 'active'; $no_active=''; break;
199                 }
200         }
201
202         return [$no_active, $all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active];
203 }
204
205 function network_query_get_sel_group(App $a)
206 {
207         $group = false;
208
209         if ($a->argc >= 2 && is_numeric($a->argv[1])) {
210                 $group = $a->argv[1];
211         }
212
213         return $group;
214 }
215
216 /**
217  * Sets the pager data and returns SQL
218  *
219  * @param App     $a      The global App
220  * @param Pager   $pager
221  * @param integer $update Used for the automatic reloading
222  * @return string SQL with the appropriate LIMIT clause
223  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
224  */
225 function networkPager(App $a, Pager $pager, $update)
226 {
227         if ($update) {
228                 // only setup pagination on initial page view
229                 return ' LIMIT 100';
230         }
231
232         if (DI::mode()->isMobile()) {
233                 $itemspage_network = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
234                         DI::config()->get('system', 'itemspage_network_mobile'));
235         } else {
236                 $itemspage_network = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
237                         DI::config()->get('system', 'itemspage_network'));
238         }
239
240         //  now that we have the user settings, see if the theme forces
241         //  a maximum item number which is lower then the user choice
242         if (($a->force_max_items > 0) && ($a->force_max_items < $itemspage_network)) {
243                 $itemspage_network = $a->force_max_items;
244         }
245
246         $pager->setItemsPerPage($itemspage_network);
247
248         return sprintf(" LIMIT %d, %d ", $pager->getStart(), $pager->getItemsPerPage());
249 }
250
251 /**
252  * Sets items as seen
253  *
254  * @param array $condition The array with the SQL condition
255  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
256  */
257 function networkSetSeen($condition)
258 {
259         if (empty($condition)) {
260                 return;
261         }
262
263         $unseen = Item::exists($condition);
264
265         if ($unseen) {
266                 Item::update(['unseen' => false], $condition);
267         }
268 }
269
270 /**
271  * Create the conversation HTML
272  *
273  * @param App     $a      The global App
274  * @param array   $items  Items of the conversation
275  * @param Pager   $pager
276  * @param string  $mode   Display mode for the conversation
277  * @param integer $update Used for the automatic reloading
278  * @param string  $ordering
279  * @return string HTML of the conversation
280  * @throws ImagickException
281  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
282  */
283 function networkConversation(App $a, $items, Pager $pager, $mode, $update, $ordering = '')
284 {
285         // Set this so that the conversation function can find out contact info for our wall-wall items
286         $a->page_contact = $a->contact;
287
288         if (!is_array($items)) {
289                 Logger::log("Expecting items to be an array. Got " . print_r($items, true));
290                 $items = [];
291         }
292
293         $o = conversation($a, $items, $mode, $update, false, $ordering, local_user());
294
295         if (!$update) {
296                 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
297                         $o .= HTML::scrollLoader();
298                 } else {
299                         $o .= $pager->renderMinimal(count($items));
300                 }
301         }
302
303         return $o;
304 }
305
306 function network_content(App $a, $update = 0, $parent = 0)
307 {
308         if (!local_user()) {
309                 return Login::form();
310         }
311
312         /// @TODO Is this really necessary? $a is already available to hooks
313         $arr = ['query' => DI::args()->getQueryString()];
314         Hook::callAll('network_content_init', $arr);
315
316         if (!empty($_GET['new']) || !empty($_GET['file'])) {
317                 $o = networkFlatView($a, $update);
318         } else {
319                 $o = networkThreadedView($a, $update, $parent);
320         }
321
322         if ($o === '') {
323                 info("No items found");
324         }
325
326         return $o;
327 }
328
329 /**
330  * Get the network content in flat view
331  *
332  * @param App     $a      The global App
333  * @param integer $update Used for the automatic reloading
334  * @return string HTML of the network content in flat view
335  * @throws ImagickException
336  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
337  * @global Pager  $pager
338  */
339 function networkFlatView(App $a, $update = 0)
340 {
341         global $pager;
342         // Rawmode is used for fetching new content at the end of the page
343         $rawmode = (isset($_GET['mode']) && ($_GET['mode'] == 'raw'));
344
345         $o = '';
346
347         $file = $_GET['file'] ?? '';
348
349         if (!$update && !$rawmode) {
350                 $tabs = network_tabs($a);
351                 $o .= $tabs;
352
353                 Nav::setSelected('network');
354
355                 $x = [
356                         'is_owner' => true,
357                         'allow_location' => $a->user['allow_location'],
358                         'default_location' => $a->user['default-location'],
359                         'nickname' => $a->user['nickname'],
360                         'lockstate' => (is_array($a->user) &&
361                         (strlen($a->user['allow_cid']) || strlen($a->user['allow_gid']) ||
362                         strlen($a->user['deny_cid']) || strlen($a->user['deny_gid'])) ? 'lock' : 'unlock'),
363                         'default_perms' => ACL::getDefaultUserPermissions($a->user),
364                         'acl' => ACL::getFullSelectorHTML(DI::page(), $a->user, true),
365                         'bang' => '',
366                         'visitor' => 'block',
367                         'profile_uid' => local_user(),
368                         'content' => '',
369                 ];
370
371                 $o .= status_editor($a, $x);
372
373                 if (!DI::config()->get('theme', 'hide_eventlist')) {
374                         $o .= Profile::getBirthdays();
375                         $o .= Profile::getEventsReminderHTML();
376                 }
377         }
378
379         $pager = new Pager(DI::l10n(), DI::args()->getQueryString());
380
381         networkPager($a, $pager, $update);
382
383         $item_params = ['order' => ['id' => true]];
384
385         if (strlen($file)) {
386                 $term_condition = ["`term` = ? AND `otype` = ? AND `type` = ? AND `uid` = ?",
387                         $file, Term::OBJECT_TYPE_POST, Term::FILE, local_user()];
388                 $term_params = ['order' => ['tid' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
389                 $result = DBA::select('term', ['oid'], $term_condition, $term_params);
390
391                 $posts = [];
392                 while ($term = DBA::fetch($result)) {
393                         $posts[] = $term['oid'];
394                 }
395                 DBA::close($result);
396
397                 if (count($posts) == 0) {
398                         return '';
399                 }
400                 $item_condition = ['uid' => local_user(), 'id' => $posts];
401         } else {
402                 $item_condition = ['uid' => local_user()];
403                 $item_params['limit'] = [$pager->getStart(), $pager->getItemsPerPage()];
404
405                 networkSetSeen(['unseen' => true, 'uid' => local_user()]);
406         }
407
408         $result = Item::selectForUser(local_user(), [], $item_condition, $item_params);
409         $items = Item::inArray($result);
410         $o .= networkConversation($a, $items, $pager, 'network-new', $update);
411
412         return $o;
413 }
414
415 /**
416  * Get the network content in threaded view
417  *
418  * @param  App     $a      The global App
419  * @param  integer $update Used for the automatic reloading
420  * @param  integer $parent
421  * @return string HTML of the network content in flat view
422  * @throws ImagickException
423  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
424  * @global Pager   $pager
425  */
426 function networkThreadedView(App $a, $update, $parent)
427 {
428         /// @TODO this will have to be converted to a static property of the converted Module\Network class
429         global $pager;
430
431         // Rawmode is used for fetching new content at the end of the page
432         $rawmode = (isset($_GET['mode']) AND ( $_GET['mode'] == 'raw'));
433
434         if (isset($_GET['last_received']) && isset($_GET['last_commented']) && isset($_GET['last_created']) && isset($_GET['last_id'])) {
435                 $last_received = DateTimeFormat::utc($_GET['last_received']);
436                 $last_commented = DateTimeFormat::utc($_GET['last_commented']);
437                 $last_created = DateTimeFormat::utc($_GET['last_created']);
438                 $last_id = intval($_GET['last_id']);
439         } else {
440                 $last_received = '';
441                 $last_commented = '';
442                 $last_created = '';
443                 $last_id = 0;
444         }
445
446         $datequery = $datequery2 = '';
447
448         $gid = 0;
449
450         $default_permissions = [];
451
452         if ($a->argc > 1) {
453                 for ($x = 1; $x < $a->argc; $x ++) {
454                         if (DI::dtFormat()->isYearMonthDay($a->argv[$x])) {
455                                 if ($datequery) {
456                                         $datequery2 = Strings::escapeHtml($a->argv[$x]);
457                                 } else {
458                                         $datequery = Strings::escapeHtml($a->argv[$x]);
459                                         $_GET['order'] = 'post';
460                                 }
461                         } elseif (intval($a->argv[$x])) {
462                                 $gid = intval($a->argv[$x]);
463                                 $default_permissions['allow_gid'] = [$gid];
464                         }
465                 }
466         }
467
468         $o = '';
469
470         $cid   = intval($_GET['cid']   ?? 0);
471         $star  = intval($_GET['star']  ?? 0);
472         $bmark = intval($_GET['bmark'] ?? 0);
473         $conv  = intval($_GET['conv']  ?? 0);
474         $order = Strings::escapeTags(($_GET['order'] ?? '') ?: 'activity');
475         $nets  =        $_GET['nets']  ?? '';
476
477         $allowedCids = [];
478         if ($cid) {
479                 $allowedCids[] = (int) $cid;
480         } elseif ($nets) {
481                 $condition = [
482                         'uid'     => local_user(),
483                         'network' => $nets,
484                         'self'    => false,
485                         'blocked' => false,
486                         'pending' => false,
487                         'archive' => false,
488                         'rel'     => [Contact::SHARING, Contact::FRIEND],
489                 ];
490                 $contactStmt = DBA::select('contact', ['id'], $condition);
491                 while ($contact = DBA::fetch($contactStmt)) {
492                         $allowedCids[] = (int) $contact['id'];
493                 }
494                 DBA::close($contactStmt);
495         }
496
497         if (count($allowedCids)) {
498                 $default_permissions['allow_cid'] = $allowedCids;
499         }
500
501         if (!$update && !$rawmode) {
502                 $tabs = network_tabs($a);
503                 $o .= $tabs;
504
505                 Nav::setSelected('network');
506
507                 $content = '';
508
509                 if ($cid) {
510                         // If $cid belongs to a communitity forum or a privat goup,.add a mention to the status editor
511                         $condition = ["`id` = ? AND (`forum` OR `prv`)", $cid];
512                         $contact = DBA::selectFirst('contact', ['addr', 'nick'], $condition);
513                         if (DBA::isResult($contact)) {
514                                 if ($contact['addr'] != '') {
515                                         $content = '!' . $contact['addr'];
516                                 } else {
517                                         $content = '!' . $contact['nick'] . '+' . $cid;
518                                 }
519                         }
520                 }
521
522                 $x = [
523                         'is_owner' => true,
524                         'allow_location' => $a->user['allow_location'],
525                         'default_location' => $a->user['default-location'],
526                         'nickname' => $a->user['nickname'],
527                         'lockstate' => ($gid || $cid || $nets || (is_array($a->user) &&
528                         (strlen($a->user['allow_cid']) || strlen($a->user['allow_gid']) ||
529                         strlen($a->user['deny_cid']) || strlen($a->user['deny_gid']))) ? 'lock' : 'unlock'),
530                         'default_perms' => ACL::getDefaultUserPermissions($a->user),
531                         'acl' => ACL::getFullSelectorHTML(DI::page(), $a->user, true, $default_permissions),
532                         'bang' => (($gid || $cid || $nets) ? '!' : ''),
533                         'visitor' => 'block',
534                         'profile_uid' => local_user(),
535                         'content' => $content,
536                 ];
537
538                 $o .= status_editor($a, $x);
539         }
540
541         // We don't have to deal with ACLs on this page. You're looking at everything
542         // that belongs to you, hence you can see all of it. We will filter by group if
543         // desired.
544
545         $sql_post_table = '';
546         $sql_options = ($star ? " AND `thread`.`starred` " : '');
547         $sql_options .= ($bmark ? sprintf(" AND `thread`.`post-type` = %d ", Item::PT_PAGE) : '');
548         $sql_extra = $sql_options;
549         $sql_extra2 = '';
550         $sql_extra3 = '';
551         $sql_table = '`thread`';
552         $sql_parent = '`iid`';
553
554         if ($update) {
555                 $sql_table = '`item`';
556                 $sql_parent = '`parent`';
557                 $sql_post_table = " INNER JOIN `thread` ON `thread`.`iid` = `item`.`parent`";
558         }
559
560         $sql_nets = (($nets) ? sprintf(" AND $sql_table.`network` = '%s' ", DBA::escape($nets)) : '');
561         $sql_tag_nets = (($nets) ? sprintf(" AND `item`.`network` = '%s' ", DBA::escape($nets)) : '');
562
563         if ($gid) {
564                 $group = DBA::selectFirst('group', ['name'], ['id' => $gid, 'uid' => local_user()]);
565                 if (!DBA::isResult($group)) {
566                         if ($update) {
567                                 exit();
568                         }
569                         notice(DI::l10n()->t('No such group') . EOL);
570                         DI::baseUrl()->redirect('network/0');
571                         // NOTREACHED
572                 }
573
574                 $contacts = Group::expand(local_user(), [$gid]);
575
576                 if ((is_array($contacts)) && count($contacts)) {
577                         $contact_str_self = '';
578
579                         $contact_str = implode(',', $contacts);
580                         $self = DBA::selectFirst('contact', ['id'], ['uid' => local_user(), 'self' => true]);
581                         if (DBA::isResult($self)) {
582                                 $contact_str_self = $self['id'];
583                         }
584
585                         $sql_post_table .= " INNER JOIN `item` AS `temp1` ON `temp1`.`id` = " . $sql_table . "." . $sql_parent;
586                         $sql_extra3 .= " AND (`thread`.`contact-id` IN ($contact_str) ";
587                         $sql_extra3 .= " OR (`thread`.`contact-id` = '$contact_str_self' AND `temp1`.`allow_gid` LIKE '" . Strings::protectSprintf('%<' . intval($gid) . '>%') . "' AND `temp1`.`private`))";
588                 } else {
589                         $sql_extra3 .= " AND false ";
590                         info(DI::l10n()->t('Group is empty'));
591                 }
592
593                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
594                         '$title' => DI::l10n()->t('Group: %s', $group['name'])
595                 ]) . $o;
596         } elseif ($cid) {
597                 $fields = ['id', 'name', 'network', 'writable', 'nurl',
598                         'forum', 'prv', 'contact-type', 'addr', 'thumb', 'location'];
599                 $condition = ["`id` = ? AND (NOT `blocked` OR `pending`)", $cid];
600                 $contact = DBA::selectFirst('contact', $fields, $condition);
601                 if (DBA::isResult($contact)) {
602                         $sql_extra = " AND " . $sql_table . ".`contact-id` = " . intval($cid);
603
604                         $entries[0] = [
605                                 'id' => 'network',
606                                 'name' => $contact['name'],
607                                 'itemurl' => ($contact['addr'] ?? '') ?: $contact['nurl'],
608                                 'thumb' => ProxyUtils::proxifyUrl($contact['thumb'], false, ProxyUtils::SIZE_THUMB),
609                                 'details' => $contact['location'],
610                         ];
611
612                         $entries[0]['account_type'] = Contact::getAccountType($contact);
613
614                         $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('viewcontact_template.tpl'), [
615                                 'contacts' => $entries,
616                                 'id' => 'network',
617                         ]) . $o;
618                 } else {
619                         notice(DI::l10n()->t('Invalid contact.') . EOL);
620                         DI::baseUrl()->redirect('network');
621                         // NOTREACHED
622                 }
623         }
624
625         if (!$gid && !$cid && !$update && !DI::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::l10n(), 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 (DI::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 = DI::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 `uri-id` FROM `tag-search-view` WHERE `name` IN
792                                 (SELECT SUBSTR(`term`, 2) FROM `search` WHERE `uid` = ? AND `term` LIKE '#%') AND `uid` = 0) AS `tag-search`
793                         ON `item`.`uri-id` = `tag-search`.`uri-id`
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(), $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         /// DI::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 }