]> git.mxchange.org Git - friendica.git/blob - mod/network.php
Use CONTACT_IS_SHARING constant instead of `rel` value
[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\ACL;
13 use Friendica\Core\Addon;
14 use Friendica\Core\Config;
15 use Friendica\Core\L10n;
16 use Friendica\Core\PConfig;
17 use Friendica\Core\System;
18 use Friendica\Database\DBM;
19 use Friendica\Model\Contact;
20 use Friendica\Model\Group;
21 use Friendica\Model\Item;
22 use Friendica\Model\Profile;
23 use Friendica\Module\Login;
24 use Friendica\Util\DateTimeFormat;
25
26 require_once 'include/conversation.php';
27 require_once 'include/items.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, false, $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, $parent = 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, $parent);
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' => ACL::getDefaultUserPermissions($a->user),
431                         'acl' => ACL::getFullSelectorHTML($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::getEventsReminderHTML();
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, $parent)
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' => ACL::getDefaultUserPermissions($a->user),
580                         'acl' => ACL::getFullSelectorHTML((($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::getEventsReminderHTML();
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         if ($conv) {
693                 $sql_extra3 .= " AND $sql_table.`mention`";
694         }
695
696         // Normal conversation view
697         if ($order === 'post') {
698                 $ordering = '`created`';
699                 $order_mode = 'created';
700         } else {
701                 $ordering = '`commented`';
702                 $order_mode = 'commented';
703         }
704
705         if ($sql_order == '') {
706                 $sql_order = "$sql_table.$ordering";
707         }
708
709         if (x($_GET, 'offset')) {
710                 $sql_range = sprintf(" AND $sql_order <= '%s'", dbesc($_GET['offset']));
711         } else {
712                 $sql_range = '';
713         }
714
715         $pager_sql = networkPager($a, $update);
716
717         $last_date = '';
718
719         switch ($order_mode) {
720                 case 'received':
721                         if ($last_received != '') {
722                                 $last_date = $last_received;
723                                 $sql_range .= sprintf(" AND $sql_table.`received` < '%s'", dbesc($last_received));
724                                 $a->set_pager_page(1);
725                                 $pager_sql = sprintf(" LIMIT %d, %d ", intval($a->pager['start']), intval($a->pager['itemspage']));
726                         }
727                         break;
728                 case 'commented':
729                         if ($last_commented != '') {
730                                 $last_date = $last_commented;
731                                 $sql_range .= sprintf(" AND $sql_table.`commented` < '%s'", dbesc($last_commented));
732                                 $a->set_pager_page(1);
733                                 $pager_sql = sprintf(" LIMIT %d, %d ", intval($a->pager['start']), intval($a->pager['itemspage']));
734                         }
735                         break;
736                 case 'created':
737                         if ($last_created != '') {
738                                 $last_date = $last_created;
739                                 $sql_range .= sprintf(" AND $sql_table.`created` < '%s'", dbesc($last_created));
740                                 $a->set_pager_page(1);
741                                 $pager_sql = sprintf(" LIMIT %d, %d ", intval($a->pager['start']), intval($a->pager['itemspage']));
742                         }
743                         break;
744                 case 'id':
745                         if (($last_id > 0) && ($sql_table == '`thread`')) {
746                                 $sql_range .= sprintf(" AND $sql_table.`iid` < '%s'", dbesc($last_id));
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         }
752
753         // Fetch a page full of parent items for this page
754         if ($update) {
755                 if (!empty($parent)) {
756                         // Load only a single thread
757                         $sql_extra4 = "`item`.`id` = ".intval($parent);
758                 } else {
759                         // Load all unseen items
760                         $sql_extra4 = "`item`.`unseen`";
761                         if (Config::get("system", "like_no_comment")) {
762                                 $sql_extra4 .= " AND `item`.`verb` = '".ACTIVITY_POST."'";
763                         }
764                         if ($order === 'post') {
765                                 // Only show toplevel posts when updating posts in this order mode
766                                 $sql_extra4 .= " AND `item`.`id` = `item`.`parent`";
767                         }
768                 }
769
770                 $r = q("SELECT `item`.`parent-uri` AS `uri`, `item`.`parent` AS `item_id`, $sql_order AS `order_date`
771                         FROM `item` $sql_post_table
772                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
773                                 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
774                                 AND (`item`.`parent-uri` != `item`.`uri` OR NOT (`contact`.`rel` < %d OR `contact`.`readonly`))
775                         WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`deleted`
776                         AND NOT `item`.`moderated` AND $sql_extra4
777                         $sql_extra3 $sql_extra $sql_range $sql_nets
778                         ORDER BY `order_date` DESC LIMIT 100",
779                         intval(CONTACT_IS_SHARING),
780                         intval(local_user())
781                 );
782         } else {
783                 $r = q("SELECT `item`.`uri`, `thread`.`iid` AS `item_id`, $sql_order AS `order_date`
784                         FROM `thread` $sql_post_table
785                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `thread`.`contact-id`
786                                 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
787                         STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
788                                 AND (`item`.`parent-uri` != `item`.`uri` OR NOT (`contact`.`rel` < %d OR `contact`.`readonly`))
789                         WHERE `thread`.`uid` = %d AND `thread`.`visible` AND NOT `thread`.`deleted`
790                         AND NOT `thread`.`moderated`
791                         $sql_extra2 $sql_extra3 $sql_range $sql_extra $sql_nets
792                         ORDER BY `order_date` DESC $pager_sql",
793                         intval(CONTACT_IS_SHARING),
794                         intval(local_user())
795                 );
796         }
797
798         // Only show it when unfiltered (no groups, no networks, ...)
799         if (in_array($nets, ['', NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS]) && (strlen($sql_extra . $sql_extra2 . $sql_extra3) == 0)) {
800                 if (DBM::is_result($r)) {
801                         $top_limit = current($r)['order_date'];
802                         $bottom_limit = end($r)['order_date'];
803                         if (empty($_SESSION['network_last_top_limit']) || ($_SESSION['network_last_top_limit'] < $top_limit)) {
804                                 $_SESSION['network_last_top_limit'] = $top_limit;
805                         }
806                 } else {
807                         $top_limit = $bottom_limit = DateTimeFormat::utcNow();
808                 }
809
810                 // When checking for updates we need to fetch from the newest date to the newest date before
811                 // Only do this, when the last stored date isn't too long ago (10 times the update interval)
812                 $browser_update = PConfig::get(local_user(), 'system', 'update_interval', 40000) / 1000;
813
814                 if (($browser_update > 0) && $update && !empty($_SESSION['network_last_date']) &&
815                         (($bottom_limit < $_SESSION['network_last_date']) || ($top_limit == $bottom_limit)) &&
816                         ((time() - $_SESSION['network_last_date_timestamp']) < ($browser_update * 10))) {
817                         $bottom_limit = $_SESSION['network_last_date'];
818                 }
819                 $_SESSION['network_last_date'] = defaults($_SESSION, 'network_last_top_limit', $top_limit);
820                 $_SESSION['network_last_date_timestamp'] = time();
821
822                 if ($last_date > $top_limit) {
823                         $top_limit = $last_date;
824                 } elseif ($a->pager['page'] == 1) {
825                         // Highest possible top limit when we are on the first page
826                         $top_limit = DateTimeFormat::utcNow();
827                 }
828
829                 $items = dba::p("SELECT `item`.`parent-uri` AS `uri`, 0 AS `item_id`, `item`.$ordering AS `order_date` FROM `item`
830                         STRAIGHT_JOIN (SELECT `oid` FROM `term` WHERE `term` IN
831                                 (SELECT SUBSTR(`term`, 2) FROM `search` WHERE `uid` = ? AND `term` LIKE '#%') AND `otype` = ? AND `type` = ? AND `uid` = 0) AS `term`
832                         ON `item`.`id` = `term`.`oid`
833                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
834                                 AND (`item`.`parent-uri` != `item`.`uri` OR NOT (`contact`.`rel` < ? OR `contact`.`readonly`))
835                         WHERE `item`.`uid` = 0 AND `item`.$ordering < ? AND `item`.$ordering > ?
836                                 AND NOT `contact`.`hidden` AND NOT `contact`.`blocked`" . $sql_tag_nets,
837                         local_user(), TERM_OBJ_POST, TERM_HASHTAG, intval(CONTACT_IS_SHARING), $top_limit, $bottom_limit);
838
839                 $data = dba::inArray($items);
840
841                 if (count($data) > 0) {
842                         $tag_top_limit = current($data)['order_date'];
843                         if ($_SESSION['network_last_date'] < $tag_top_limit) {
844                                 $_SESSION['network_last_date'] = $tag_top_limit;
845                         }
846
847                         logger('Tagged items: ' . count($data) . ' - ' . $bottom_limit . ' - ' . $top_limit . ' - ' . local_user().' - '.(int)$update);
848                         $s = [];
849                         foreach ($r as $item) {
850                                 $s[$item['uri']] = $item;
851                         }
852                         foreach ($data as $item) {
853                                 $s[$item['uri']] = $item;
854                         }
855                         $r = $s;
856                 }
857         }
858
859         $parents_str = '';
860         $date_offset = '';
861
862         $items = $r;
863
864         if (DBM::is_result($items)) {
865                 $parents_arr = [];
866
867                 foreach ($items as $item) {
868                         if ($date_offset < $item['order_date']) {
869                                 $date_offset = $item['order_date'];
870                         }
871                         if (!in_array($item['item_id'], $parents_arr) && ($item['item_id'] > 0)) {
872                                 $parents_arr[] = $item['item_id'];
873                         }
874                 }
875                 $parents_str = implode(', ', $parents_arr);
876         }
877
878         if (x($_GET, 'offset')) {
879                 $date_offset = $_GET['offset'];
880         }
881
882         $a->page_offset = $date_offset;
883
884         // We aren't going to try and figure out at the item, group, and page
885         // level which items you've seen and which you haven't. If you're looking
886         // at the top level network page just mark everything seen.
887
888         if (!$gid && !$cid && !$star) {
889                 $condition = ['unseen' => true, 'uid' => local_user()];
890                 networkSetSeen($condition);
891         } elseif ($parents_str) {
892                 $condition = ["`uid` = ? AND `unseen` AND `parent` IN (" . dbesc($parents_str) . ")", local_user()];
893                 networkSetSeen($condition);
894         }
895
896
897         $mode = 'network';
898         $o .= networkConversation($a, $items, $mode, $update, $ordering);
899
900         return $o;
901 }
902
903 /**
904  * @brief Get the network tabs menu
905  *
906  * @param App $a The global App
907  * @return string Html of the networktab
908  */
909 function network_tabs(App $a)
910 {
911         // item filter tabs
912         /// @TODO fix this logic, reduce duplication
913         /// $a->page['content'] .= '<div class="tabs-wrapper">';
914         list($no_active, $all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active, $spam_active) = network_query_get_sel_tab($a);
915
916         // if no tabs are selected, defaults to comments
917         if ($no_active == 'active') {
918                 $all_active = 'active';
919         }
920
921         $cmd = $a->cmd;
922
923         // tabs
924         $tabs = [
925                 [
926                         'label' => L10n::t('Commented Order'),
927                         'url'   => str_replace('/new', '', $cmd) . '?f=&order=comment' . ((x($_GET,'cid')) ? '&cid=' . $_GET['cid'] : ''),
928                         'sel'   => $all_active,
929                         'title' => L10n::t('Sort by Comment Date'),
930                         'id'    => 'commented-order-tab',
931                         'accesskey' => 'e',
932                 ],
933                 [
934                         'label' => L10n::t('Posted Order'),
935                         'url'   => str_replace('/new', '', $cmd) . '?f=&order=post' . ((x($_GET,'cid')) ? '&cid=' . $_GET['cid'] : ''),
936                         'sel'   => $postord_active,
937                         'title' => L10n::t('Sort by Post Date'),
938                         'id'    => 'posted-order-tab',
939                         'accesskey' => 't',
940                 ],
941         ];
942
943         if (Feature::isEnabled(local_user(), 'personal_tab')) {
944                 $tabs[] = [
945                         'label' => L10n::t('Personal'),
946                         'url'   => str_replace('/new', '', $cmd) . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : '/?f=') . '&conv=1',
947                         'sel'   => $conv_active,
948                         'title' => L10n::t('Posts that mention or involve you'),
949                         'id'    => 'personal-tab',
950                         'accesskey' => 'r',
951                 ];
952         }
953
954         if (Feature::isEnabled(local_user(), 'new_tab')) {
955                 $tabs[] = [
956                         'label' => L10n::t('New'),
957                         'url'   => 'network/new' . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : ''),
958                         'sel'   => $new_active,
959                         'title' => L10n::t('Activity Stream - by date'),
960                         'id'    => 'activitiy-by-date-tab',
961                         'accesskey' => 'w',
962                 ];
963         }
964
965         if (Feature::isEnabled(local_user(), 'link_tab')) {
966                 $tabs[] = [
967                         'label' => L10n::t('Shared Links'),
968                         'url'   => str_replace('/new', '', $cmd) . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : '/?f=') . '&bmark=1',
969                         'sel'   => $bookmarked_active,
970                         'title' => L10n::t('Interesting Links'),
971                         'id'    => 'shared-links-tab',
972                         'accesskey' => 'b',
973                 ];
974         }
975
976         if (Feature::isEnabled(local_user(), 'star_posts')) {
977                 $tabs[] = [
978                         'label' => L10n::t('Starred'),
979                         'url'   => str_replace('/new', '', $cmd) . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : '/?f=') . '&star=1',
980                         'sel'   => $starred_active,
981                         'title' => L10n::t('Favourite Posts'),
982                         'id'    => 'starred-posts-tab',
983                         'accesskey' => 'm',
984                 ];
985         }
986
987         // save selected tab, but only if not in file mode
988         if (!x($_GET, 'file')) {
989                 PConfig::set(local_user(), 'network.view', 'tab.selected', [
990                         $all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active, $spam_active
991                 ]);
992         }
993
994         $arr = ['tabs' => $tabs];
995         Addon::callHooks('network_tabs', $arr);
996
997         $tpl = get_markup_template('common_tabs.tpl');
998
999         return replace_macros($tpl, ['$tabs' => $arr['tabs']]);
1000
1001         // --- end item filter tabs
1002 }