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