]> git.mxchange.org Git - friendica.git/blob - mod/network.php
Ops, one more left ...
[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\Protocol;
18 use Friendica\Core\System;
19 use Friendica\Database\DBA;
20 use Friendica\Model\Contact;
21 use Friendica\Model\Group;
22 use Friendica\Model\Item;
23 use Friendica\Model\Profile;
24 use Friendica\Module\Login;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\Proxy as ProxyUtils;
27
28 require_once 'include/conversation.php';
29 require_once 'include/items.php';
30
31 function network_init(App $a)
32 {
33         if (!local_user()) {
34                 notice(L10n::t('Permission denied.') . EOL);
35                 return;
36         }
37
38         $search = (x($_GET, 'search') ? escape_tags($_GET['search']) : '');
39
40         if (($search != '') && !empty($_GET['submit'])) {
41                 goaway('search?search=' . urlencode($search));
42         }
43
44         if (x($_GET, 'save')) {
45                 $exists = DBA::exists('search', ['uid' => local_user(), 'term' => $search]);
46                 if (!$exists) {
47                         DBA::insert('search', ['uid' => local_user(), 'term' => $search]);
48                 }
49         }
50         if (x($_GET, 'remove')) {
51                 DBA::delete('search', ['uid' => local_user(), 'term' => $search]);
52         }
53
54         $is_a_date_query = false;
55
56         $group_id = (($a->argc > 1 && is_numeric($a->argv[1])) ? intval($a->argv[1]) : 0);
57
58         $cid = 0;
59         if (x($_GET, 'cid') && intval($_GET['cid']) != 0) {
60                 $cid = $_GET['cid'];
61                 $_GET['nets'] = 'all';
62                 $group_id = 0;
63         }
64
65         if ($a->argc > 1) {
66                 for ($x = 1; $x < $a->argc; $x ++) {
67                         if (is_a_date_arg($a->argv[$x])) {
68                                 $is_a_date_query = true;
69                                 break;
70                         }
71                 }
72         }
73
74         // convert query string to array. remove friendica args
75         $query_array = [];
76         $query_string = str_replace($a->cmd . '?', '', $a->query_string);
77         parse_str($query_string, $query_array);
78         array_shift($query_array);
79
80         // fetch last used network view and redirect if needed
81         if (!$is_a_date_query) {
82                 $sel_nets = defaults($_GET, 'nets', false);
83                 $sel_tabs = network_query_get_sel_tab($a);
84                 $sel_groups = network_query_get_sel_group($a);
85                 $last_sel_tabs = PConfig::get(local_user(), 'network.view', 'tab.selected');
86
87                 $remember_tab = ($sel_tabs[0] === 'active' && is_array($last_sel_tabs) && $last_sel_tabs[0] !== 'active');
88
89                 $net_baseurl = '/network';
90                 $net_args = [];
91
92                 if ($sel_groups !== false) {
93                         $net_baseurl .= '/' . $sel_groups;
94                 }
95
96                 if ($remember_tab) {
97                         // redirect if current selected tab is '/network' and
98                         // last selected tab is _not_ '/network?f=&order=comment'.
99                         // and this isn't a date query
100
101                         $tab_baseurls = [
102                                 '',     //all
103                                 '',     //postord
104                                 '',     //conv
105                                 '/new', //new
106                                 '',     //starred
107                                 '',     //bookmarked
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                         ];
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  *
222  * @return Array ($no_active, $comment_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_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         $postord_active = '';
233
234         if (($a->argc > 1 && $a->argv[1] === 'new') || ($a->argc > 2 && $a->argv[2] === 'new')) {
235                 $new_active = 'active';
236         }
237
238         if (x($_GET, 'star')) {
239                 $starred_active = 'active';
240         }
241
242         if (x($_GET, 'bmark')) {
243                 $bookmarked_active = 'active';
244         }
245
246         if (x($_GET, 'conv')) {
247                 $conv_active = 'active';
248         }
249
250         if (($new_active == '') && ($starred_active == '') && ($bookmarked_active == '') && ($conv_active == '')) {
251                 $no_active = 'active';
252         }
253
254         if ($no_active == 'active' && x($_GET, 'order')) {
255                 switch($_GET['order']) {
256                         case 'post'    : $postord_active = 'active'; $no_active=''; break;
257                         case 'comment' : $all_active     = 'active'; $no_active=''; break;
258                 }
259         }
260
261         return [$no_active, $all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active];
262 }
263
264 function network_query_get_sel_group(App $a)
265 {
266         $group = false;
267
268         if ($a->argc >= 2 && is_numeric($a->argv[1])) {
269                 $group = $a->argv[1];
270         }
271
272         return $group;
273 }
274
275 /**
276  * @brief Sets the pager data and returns SQL
277  *
278  * @param App $a The global App
279  * @param integer $update Used for the automatic reloading
280  * @return string SQL with the appropriate LIMIT clause
281  */
282 function networkPager($a, $update)
283 {
284         if ($update) {
285                 // only setup pagination on initial page view
286                 return ' LIMIT 100';
287         }
288
289         //  check if we serve a mobile device and get the user settings
290         //  accordingly
291         if ($a->is_mobile) {
292                 $itemspage_network = PConfig::get(local_user(), 'system', 'itemspage_mobile_network');
293                 $itemspage_network = ((intval($itemspage_network)) ? $itemspage_network : 20);
294         } else {
295                 $itemspage_network = PConfig::get(local_user(), 'system', 'itemspage_network');
296                 $itemspage_network = ((intval($itemspage_network)) ? $itemspage_network : 40);
297         }
298
299         //  now that we have the user settings, see if the theme forces
300         //  a maximum item number which is lower then the user choice
301         if (($a->force_max_items > 0) && ($a->force_max_items < $itemspage_network)) {
302                 $itemspage_network = $a->force_max_items;
303         }
304
305         $a->set_pager_itemspage($itemspage_network);
306
307         return sprintf(" LIMIT %d, %d ", intval($a->pager['start']), intval($a->pager['itemspage']));
308 }
309
310 /**
311  * @brief Sets items as seen
312  *
313  * @param array $condition The array with the SQL condition
314  */
315 function networkSetSeen($condition)
316 {
317         if (empty($condition)) {
318                 return;
319         }
320
321         $unseen = DBA::exists('item', $condition);
322
323         if ($unseen) {
324                 $r = Item::update(['unseen' => false], $condition);
325         }
326 }
327
328 /**
329  * @brief Create the conversation HTML
330  *
331  * @param App $a The global App
332  * @param array $items Items of the conversation
333  * @param string $mode Display mode for the conversation
334  * @param integer $update Used for the automatic reloading
335  * @return string HTML of the conversation
336  */
337 function networkConversation($a, $items, $mode, $update, $ordering = '')
338 {
339         // Set this so that the conversation function can find out contact info for our wall-wall items
340         $a->page_contact = $a->contact;
341
342         $o = conversation($a, $items, $mode, $update, false, $ordering, local_user());
343
344         if (!$update) {
345                 if (PConfig::get(local_user(), 'system', 'infinite_scroll')) {
346                         $o .= scroll_loader();
347                 } else {
348                         $o .= alt_pager($a, count($items));
349                 }
350         }
351
352         return $o;
353 }
354
355 function network_content(App $a, $update = 0, $parent = 0)
356 {
357         if (!local_user()) {
358                 return Login::form();
359         }
360
361         /// @TODO Is this really necessary? $a is already available to hooks
362         $arr = ['query' => $a->query_string];
363         Addon::callHooks('network_content_init', $arr);
364
365         $flat_mode = false;
366
367         if ($a->argc > 1) {
368                 for ($x = 1; $x < $a->argc; $x ++) {
369                         if ($a->argv[$x] === 'new') {
370                                 $flat_mode = true;
371                         }
372                 }
373         }
374
375         if (x($_GET, 'file')) {
376                 $flat_mode = true;
377         }
378
379         if ($flat_mode) {
380                 $o = networkFlatView($a, $update);
381         } else {
382                 $o = networkThreadedView($a, $update, $parent);
383         }
384
385         return $o;
386 }
387
388 /**
389  * @brief Get the network content in flat view
390  *
391  * @param App $a The global App
392  * @param integer $update Used for the automatic reloading
393  * @return string HTML of the network content in flat view
394  */
395 function networkFlatView(App $a, $update = 0)
396 {
397         // Rawmode is used for fetching new content at the end of the page
398         $rawmode = (isset($_GET['mode']) && ($_GET['mode'] == 'raw'));
399
400         if (isset($_GET['last_id'])) {
401                 $last_id = intval($_GET['last_id']);
402         } else {
403                 $last_id = 0;
404         }
405
406         $o = '';
407
408         $file = ((x($_GET, 'file')) ? $_GET['file'] : '');
409
410         if (!$update && !$rawmode) {
411                 $tabs = network_tabs($a);
412                 $o .= $tabs;
413
414                 Nav::setSelected('network');
415
416                 $x = [
417                         'is_owner' => true,
418                         'allow_location' => $a->user['allow_location'],
419                         'default_location' => $a->user['default-location'],
420                         'nickname' => $a->user['nickname'],
421                         'lockstate' => (((is_array($a->user) &&
422                         ((strlen($a->user['allow_cid'])) || (strlen($a->user['allow_gid'])) ||
423                         (strlen($a->user['deny_cid'])) || (strlen($a->user['deny_gid']))))) ? 'lock' : 'unlock'),
424                         'default_perms' => ACL::getDefaultUserPermissions($a->user),
425                         'acl' => ACL::getFullSelectorHTML($a->user, true),
426                         'bang' => '',
427                         'visitor' => 'block',
428                         'profile_uid' => local_user(),
429                         'content' => '',
430                 ];
431
432                 $o .= status_editor($a, $x);
433
434                 if (!Config::get('theme', 'hide_eventlist')) {
435                         $o .= Profile::getBirthdays();
436                         $o .= Profile::getEventsReminderHTML();
437                 }
438         }
439
440         $pager_sql = networkPager($a, $update);
441
442         if (strlen($file)) {
443                 $condition = ["`term` = ? AND `otype` = ? AND `type` = ? AND `uid` = ?",
444                         $file, TERM_OBJ_POST, TERM_FILE, local_user()];
445                 $params = ['order' => ['tid' => true], 'limit' => [$a->pager['start'], $a->pager['itemspage']]];
446                 $result = DBA::select('term', ['oid'], $condition);
447
448                 $posts = [];
449                 while ($term = DBA::fetch($result)) {
450                         $posts[] = $term['oid'];
451                 }
452                 DBA::close($terms);
453
454                 $condition = ['uid' => local_user(), 'id' => $posts];
455         } else {
456                 $condition = ['uid' => local_user()];
457         }
458
459         $params = ['order' => ['id' => true], 'limit' => [$a->pager['start'], $a->pager['itemspage']]];
460         $result = Item::selectForUser(local_user(), [], $condition, $params);
461         $items = Item::inArray($result);
462
463         $condition = ['unseen' => true, 'uid' => local_user()];
464         networkSetSeen($condition);
465
466         $o .= networkConversation($a, $items, 'network-new', $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, $parent)
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 = DateTimeFormat::utc($_GET['last_received']);
485                 $last_commented = DateTimeFormat::utc($_GET['last_commented']);
486                 $last_created = DateTimeFormat::utc($_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 (DBA::isResult($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' => ACL::getDefaultUserPermissions($a->user),
579                         'acl' => ACL::getFullSelectorHTML((($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 ? sprintf(" AND `thread`.`post-type` = %d ", Item::PT_PAGE) : '');
596         $sql_extra = $sql_options;
597         $sql_extra2 = '';
598         $sql_extra3 = '';
599         $sql_table = '`thread`';
600         $sql_parent = '`iid`';
601         $sql_order = '';
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' ", DBA::escape($nets)) : '');
610         $sql_tag_nets = (($nets) ? sprintf(" AND `item`.`network` = '%s' ", DBA::escape($nets)) : '');
611
612         if ($gid) {
613                 $group = DBA::selectFirst('group', ['name'], ['id' => $gid, 'uid' => local_user()]);
614                 if (!DBA::isResult($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' => local_user(), 'self' => true]);
630                         if (DBA::isResult($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 (DBA::isResult($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' => ProxyUtils::proxifyUrl($contact['thumb'], false, ProxyUtils::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'] === Protocol::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                                 DBA::escape(DateTimeFormat::convert($datequery, 'UTC', date_default_timezone_get()))));
686         }
687         if ($datequery2) {
688                 $sql_extra3 .= protect_sprintf(sprintf(" AND $sql_table.created >= '%s' ",
689                                 DBA::escape(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         $sql_order = "$sql_table.$ordering";
706
707         if (x($_GET, 'offset')) {
708                 $sql_range = sprintf(" AND $sql_order <= '%s'", DBA::escape($_GET['offset']));
709         } else {
710                 $sql_range = '';
711         }
712
713         $pager_sql = networkPager($a, $update);
714
715         $last_date = '';
716
717         switch ($order_mode) {
718                 case 'received':
719                         if ($last_received != '') {
720                                 $last_date = $last_received;
721                                 $sql_range .= sprintf(" AND $sql_table.`received` < '%s'", DBA::escape($last_received));
722                                 $a->set_pager_page(1);
723                                 $pager_sql = sprintf(" LIMIT %d, %d ", intval($a->pager['start']), intval($a->pager['itemspage']));
724                         }
725                         break;
726                 case 'commented':
727                         if ($last_commented != '') {
728                                 $last_date = $last_commented;
729                                 $sql_range .= sprintf(" AND $sql_table.`commented` < '%s'", DBA::escape($last_commented));
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 'created':
735                         if ($last_created != '') {
736                                 $last_date = $last_created;
737                                 $sql_range .= sprintf(" AND $sql_table.`created` < '%s'", DBA::escape($last_created));
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 'id':
743                         if (($last_id > 0) && ($sql_table == '`thread`')) {
744                                 $sql_range .= sprintf(" AND $sql_table.`iid` < '%s'", DBA::escape($last_id));
745                                 $a->set_pager_page(1);
746                                 $pager_sql = sprintf(" LIMIT %d, %d ", intval($a->pager['start']), intval($a->pager['itemspage']));
747                         }
748                         break;
749         }
750
751         // Fetch a page full of parent items for this page
752         if ($update) {
753                 if (!empty($parent)) {
754                         // Load only a single thread
755                         $sql_extra4 = "`item`.`id` = ".intval($parent);
756                 } else {
757                         // Load all unseen items
758                         $sql_extra4 = "`item`.`unseen`";
759                         if (Config::get("system", "like_no_comment")) {
760                                 $sql_extra4 .= " AND `item`.`gravity` IN (" . GRAVITY_PARENT . "," . GRAVITY_COMMENT . ")";
761                         }
762                         if ($order === 'post') {
763                                 // Only show toplevel posts when updating posts in this order mode
764                                 $sql_extra4 .= " AND `item`.`id` = `item`.`parent`";
765                         }
766                 }
767
768                 $r = q("SELECT `item`.`parent-uri` AS `uri`, `item`.`parent` AS `item_id`, $sql_order AS `order_date`
769                         FROM `item` $sql_post_table
770                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
771                                 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
772                                 AND (`item`.`parent-uri` != `item`.`uri`
773                                         OR `contact`.`uid` = `item`.`uid` AND `contact`.`self`
774                                         OR `contact`.`rel` IN (%d, %d) AND NOT `contact`.`readonly`)
775                         LEFT JOIN `user-item` ON `user-item`.`iid` = `item`.`id` AND `user-item`.`uid` = %d
776                         WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`deleted`
777                         AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
778                         AND NOT `item`.`moderated` AND $sql_extra4
779                         $sql_extra3 $sql_extra $sql_range $sql_nets
780                         ORDER BY `order_date` DESC LIMIT 100",
781                         intval(Contact::SHARING),
782                         intval(Contact::FRIEND),
783                         intval(local_user()),
784                         intval(local_user())
785                 );
786         } else {
787                 $r = q("SELECT `item`.`uri`, `thread`.`iid` AS `item_id`, $sql_order AS `order_date`
788                         FROM `thread` $sql_post_table
789                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `thread`.`contact-id`
790                                 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
791                         STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
792                                 AND (`item`.`parent-uri` != `item`.`uri`
793                                         OR `contact`.`uid` = `item`.`uid` AND `contact`.`self`
794                                         OR `contact`.`rel` IN (%d, %d) AND NOT `contact`.`readonly`)
795                         LEFT JOIN `user-item` ON `user-item`.`iid` = `item`.`id` AND `user-item`.`uid` = %d
796                         WHERE `thread`.`uid` = %d AND `thread`.`visible` AND NOT `thread`.`deleted`
797                         AND NOT `thread`.`moderated`
798                         AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
799                         $sql_extra2 $sql_extra3 $sql_range $sql_extra $sql_nets
800                         ORDER BY `order_date` DESC $pager_sql",
801                         intval(Contact::SHARING),
802                         intval(Contact::FRIEND),
803                         intval(local_user()),
804                         intval(local_user())
805                 );
806         }
807
808         // Only show it when unfiltered (no groups, no networks, ...)
809         if (in_array($nets, ['', Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]) && (strlen($sql_extra . $sql_extra2 . $sql_extra3) == 0)) {
810                 if (DBA::isResult($r)) {
811                         $top_limit = current($r)['order_date'];
812                         $bottom_limit = end($r)['order_date'];
813                         if (empty($_SESSION['network_last_top_limit']) || ($_SESSION['network_last_top_limit'] < $top_limit)) {
814                                 $_SESSION['network_last_top_limit'] = $top_limit;
815                         }
816                 } else {
817                         $top_limit = $bottom_limit = DateTimeFormat::utcNow();
818                 }
819
820                 // When checking for updates we need to fetch from the newest date to the newest date before
821                 // Only do this, when the last stored date isn't too long ago (10 times the update interval)
822                 $browser_update = PConfig::get(local_user(), 'system', 'update_interval', 40000) / 1000;
823
824                 if (($browser_update > 0) && $update && !empty($_SESSION['network_last_date']) &&
825                         (($bottom_limit < $_SESSION['network_last_date']) || ($top_limit == $bottom_limit)) &&
826                         ((time() - $_SESSION['network_last_date_timestamp']) < ($browser_update * 10))) {
827                         $bottom_limit = $_SESSION['network_last_date'];
828                 }
829                 $_SESSION['network_last_date'] = defaults($_SESSION, 'network_last_top_limit', $top_limit);
830                 $_SESSION['network_last_date_timestamp'] = time();
831
832                 if ($last_date > $top_limit) {
833                         $top_limit = $last_date;
834                 } elseif ($a->pager['page'] == 1) {
835                         // Highest possible top limit when we are on the first page
836                         $top_limit = DateTimeFormat::utcNow();
837                 }
838
839                 $items = DBA::p("SELECT `item`.`parent-uri` AS `uri`, 0 AS `item_id`, `item`.$ordering AS `order_date`, `author`.`url` AS `author-link` FROM `item`
840                         STRAIGHT_JOIN (SELECT `oid` FROM `term` WHERE `term` IN
841                                 (SELECT SUBSTR(`term`, 2) FROM `search` WHERE `uid` = ? AND `term` LIKE '#%') AND `otype` = ? AND `type` = ? AND `uid` = 0) AS `term`
842                         ON `item`.`id` = `term`.`oid`
843                         STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = `item`.`author-id`
844                         WHERE `item`.`uid` = 0 AND `item`.$ordering < ? AND `item`.$ordering > ?
845                                 AND NOT `author`.`hidden` AND NOT `author`.`blocked`" . $sql_tag_nets,
846                         local_user(), TERM_OBJ_POST, TERM_HASHTAG,
847                         $top_limit, $bottom_limit);
848
849                 $data = DBA::toArray($items);
850
851                 if (count($data) > 0) {
852                         $tag_top_limit = current($data)['order_date'];
853                         if ($_SESSION['network_last_date'] < $tag_top_limit) {
854                                 $_SESSION['network_last_date'] = $tag_top_limit;
855                         }
856
857                         logger('Tagged items: ' . count($data) . ' - ' . $bottom_limit . ' - ' . $top_limit . ' - ' . local_user().' - '.(int)$update);
858                         $s = [];
859                         foreach ($r as $item) {
860                                 $s[$item['uri']] = $item;
861                         }
862                         foreach ($data as $item) {
863                                 // Don't show hash tag posts from blocked or ignored contacts
864                                 $condition = ["`nurl` = ? AND `uid` = ? AND (`blocked` OR `readonly`)",
865                                         normalise_link($item['author-link']), local_user()];
866                                 if (!DBA::exists('contact', $condition)) {
867                                         $s[$item['uri']] = $item;
868                                 }
869                         }
870                         $r = $s;
871                 }
872         }
873
874         $parents_str = '';
875         $date_offset = '';
876
877         $items = $r;
878
879         if (DBA::isResult($items)) {
880                 $parents_arr = [];
881
882                 foreach ($items as $item) {
883                         if ($date_offset < $item['order_date']) {
884                                 $date_offset = $item['order_date'];
885                         }
886                         if (!in_array($item['item_id'], $parents_arr) && ($item['item_id'] > 0)) {
887                                 $parents_arr[] = $item['item_id'];
888                         }
889                 }
890                 $parents_str = implode(', ', $parents_arr);
891         }
892
893         if (x($_GET, 'offset')) {
894                 $date_offset = $_GET['offset'];
895         }
896
897         $a->page_offset = $date_offset;
898
899         // We aren't going to try and figure out at the item, group, and page
900         // level which items you've seen and which you haven't. If you're looking
901         // at the top level network page just mark everything seen.
902
903         if (!$gid && !$cid && !$star) {
904                 $condition = ['unseen' => true, 'uid' => local_user()];
905                 networkSetSeen($condition);
906         } elseif ($parents_str) {
907                 $condition = ["`uid` = ? AND `unseen` AND `parent` IN (" . DBA::escape($parents_str) . ")", local_user()];
908                 networkSetSeen($condition);
909         }
910
911
912         $mode = 'network';
913         $o .= networkConversation($a, $items, $mode, $update, $ordering);
914
915         return $o;
916 }
917
918 /**
919  * @brief Get the network tabs menu
920  *
921  * @param App $a The global App
922  * @return string Html of the networktab
923  */
924 function network_tabs(App $a)
925 {
926         // item filter tabs
927         /// @TODO fix this logic, reduce duplication
928         /// $a->page['content'] .= '<div class="tabs-wrapper">';
929         list($no_active, $all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active) = network_query_get_sel_tab($a);
930
931         // if no tabs are selected, defaults to comments
932         if ($no_active == 'active') {
933                 $all_active = 'active';
934         }
935
936         $cmd = $a->cmd;
937
938         // tabs
939         $tabs = [
940                 [
941                         'label' => L10n::t('Commented Order'),
942                         'url'   => str_replace('/new', '', $cmd) . '?f=&order=comment' . ((x($_GET,'cid')) ? '&cid=' . $_GET['cid'] : ''),
943                         'sel'   => $all_active,
944                         'title' => L10n::t('Sort by Comment Date'),
945                         'id'    => 'commented-order-tab',
946                         'accesskey' => 'e',
947                 ],
948                 [
949                         'label' => L10n::t('Posted Order'),
950                         'url'   => str_replace('/new', '', $cmd) . '?f=&order=post' . ((x($_GET,'cid')) ? '&cid=' . $_GET['cid'] : ''),
951                         'sel'   => $postord_active,
952                         'title' => L10n::t('Sort by Post Date'),
953                         'id'    => 'posted-order-tab',
954                         'accesskey' => 't',
955                 ],
956         ];
957
958         if (Feature::isEnabled(local_user(), 'personal_tab')) {
959                 $tabs[] = [
960                         'label' => L10n::t('Personal'),
961                         'url'   => str_replace('/new', '', $cmd) . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : '/?f=') . '&conv=1',
962                         'sel'   => $conv_active,
963                         'title' => L10n::t('Posts that mention or involve you'),
964                         'id'    => 'personal-tab',
965                         'accesskey' => 'r',
966                 ];
967         }
968
969         if (Feature::isEnabled(local_user(), 'new_tab')) {
970                 $tabs[] = [
971                         'label' => L10n::t('New'),
972                         'url'   => 'network/new' . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : ''),
973                         'sel'   => $new_active,
974                         'title' => L10n::t('Activity Stream - by date'),
975                         'id'    => 'activitiy-by-date-tab',
976                         'accesskey' => 'w',
977                 ];
978         }
979
980         if (Feature::isEnabled(local_user(), 'link_tab')) {
981                 $tabs[] = [
982                         'label' => L10n::t('Shared Links'),
983                         'url'   => str_replace('/new', '', $cmd) . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : '/?f=') . '&bmark=1',
984                         'sel'   => $bookmarked_active,
985                         'title' => L10n::t('Interesting Links'),
986                         'id'    => 'shared-links-tab',
987                         'accesskey' => 'b',
988                 ];
989         }
990
991         if (Feature::isEnabled(local_user(), 'star_posts')) {
992                 $tabs[] = [
993                         'label' => L10n::t('Starred'),
994                         'url'   => str_replace('/new', '', $cmd) . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : '/?f=') . '&star=1',
995                         'sel'   => $starred_active,
996                         'title' => L10n::t('Favourite Posts'),
997                         'id'    => 'starred-posts-tab',
998                         'accesskey' => 'm',
999                 ];
1000         }
1001
1002         // save selected tab, but only if not in file mode
1003         if (!x($_GET, 'file')) {
1004                 PConfig::set(local_user(), 'network.view', 'tab.selected', [
1005                         $all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active
1006                 ]);
1007         }
1008
1009         $arr = ['tabs' => $tabs];
1010         Addon::callHooks('network_tabs', $arr);
1011
1012         $tpl = get_markup_template('common_tabs.tpl');
1013
1014         return replace_macros($tpl, ['$tabs' => $arr['tabs']]);
1015
1016         // --- end item filter tabs
1017 }