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