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