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