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