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