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