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