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