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