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