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