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