Merge pull request #5711 from annando/and-again
[friendica.git/.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 = Item::exists($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($result);
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         $default_permissions = [];
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                                 $default_permissions = ['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                 $default_permissions = ['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                         $default_permissions = ['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 (DBA::isResult($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($a->user, true, $default_permissions),
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 ? sprintf(" AND `thread`.`post-type` = %d ", Item::PT_PAGE) : '');
598         $sql_extra = $sql_options;
599         $sql_extra2 = '';
600         $sql_extra3 = '';
601         $sql_table = '`thread`';
602         $sql_parent = '`iid`';
603         $sql_order = '';
604
605         if ($update) {
606                 $sql_table = '`item`';
607                 $sql_parent = '`parent`';
608                 $sql_post_table = " INNER JOIN `thread` ON `thread`.`iid` = `item`.`parent`";
609         }
610
611         $sql_nets = (($nets) ? sprintf(" AND $sql_table.`network` = '%s' ", DBA::escape($nets)) : '');
612         $sql_tag_nets = (($nets) ? sprintf(" AND `item`.`network` = '%s' ", DBA::escape($nets)) : '');
613
614         if ($gid) {
615                 $group = DBA::selectFirst('group', ['name'], ['id' => $gid, 'uid' => local_user()]);
616                 if (!DBA::isResult($group)) {
617                         if ($update) {
618                                 killme();
619                         }
620                         notice(L10n::t('No such group') . EOL);
621                         goaway('network/0');
622                         // NOTREACHED
623                 }
624
625                 $contacts = Group::expand([$gid]);
626
627                 if ((is_array($contacts)) && count($contacts)) {
628                         $contact_str_self = '';
629
630                         $contact_str = implode(',', $contacts);
631                         $self = DBA::selectFirst('contact', ['id'], ['uid' => local_user(), 'self' => true]);
632                         if (DBA::isResult($self)) {
633                                 $contact_str_self = $self['id'];
634                         }
635
636                         $sql_post_table .= " INNER JOIN `item` AS `temp1` ON `temp1`.`id` = " . $sql_table . "." . $sql_parent;
637                         $sql_extra3 .= " AND (`thread`.`contact-id` IN ($contact_str) ";
638                         $sql_extra3 .= " OR (`thread`.`contact-id` = '$contact_str_self' AND `temp1`.`allow_gid` LIKE '" . protect_sprintf('%<' . intval($gid) . '>%') . "' AND `temp1`.`private`))";
639                 } else {
640                         $sql_extra3 .= " AND false ";
641                         info(L10n::t('Group is empty'));
642                 }
643
644                 $o = replace_macros(get_markup_template('section_title.tpl'), [
645                         '$title' => L10n::t('Group: %s', $group['name'])
646                 ]) . $o;
647         } elseif ($cid) {
648                 $fields = ['id', 'name', 'network', 'writable', 'nurl',
649                         'forum', 'prv', 'contact-type', 'addr', 'thumb', 'location'];
650                 $condition = ["`id` = ? AND (NOT `blocked` OR `pending`)", $cid];
651                 $contact = DBA::selectFirst('contact', $fields, $condition);
652                 if (DBA::isResult($contact)) {
653                         $sql_extra = " AND " . $sql_table . ".`contact-id` = " . intval($cid);
654
655                         $entries[0] = [
656                                 'id' => 'network',
657                                 'name' => htmlentities($contact['name']),
658                                 'itemurl' => defaults($contact, 'addr', $contact['nurl']),
659                                 'thumb' => ProxyUtils::proxifyUrl($contact['thumb'], false, ProxyUtils::SIZE_THUMB),
660                                 'details' => $contact['location'],
661                         ];
662
663                         $entries[0]['account_type'] = Contact::getAccountType($contact);
664
665                         $o = replace_macros(get_markup_template('viewcontact_template.tpl'), [
666                                 'contacts' => $entries,
667                                 'id' => 'network',
668                         ]) . $o;
669
670                         if ($contact['network'] === Protocol::OSTATUS && $contact['writable'] && !PConfig::get(local_user(),'system','nowarn_insecure')) {
671                                 notice(L10n::t('Private messages to this person are at risk of public disclosure.') . EOL);
672                         }
673                 } else {
674                         notice(L10n::t('Invalid contact.') . EOL);
675                         goaway('network');
676                         // NOTREACHED
677                 }
678         }
679
680         if (!$gid && !$cid && !$update && !Config::get('theme', 'hide_eventlist')) {
681                 $o .= Profile::getBirthdays();
682                 $o .= Profile::getEventsReminderHTML();
683         }
684
685         if ($datequery) {
686                 $sql_extra3 .= protect_sprintf(sprintf(" AND $sql_table.created <= '%s' ",
687                                 DBA::escape(DateTimeFormat::convert($datequery, 'UTC', date_default_timezone_get()))));
688         }
689         if ($datequery2) {
690                 $sql_extra3 .= protect_sprintf(sprintf(" AND $sql_table.created >= '%s' ",
691                                 DBA::escape(DateTimeFormat::convert($datequery2, 'UTC', date_default_timezone_get()))));
692         }
693
694         if ($conv) {
695                 $sql_extra3 .= " AND $sql_table.`mention`";
696         }
697
698         // Normal conversation view
699         if ($order === 'post') {
700                 $ordering = '`created`';
701                 $order_mode = 'created';
702         } else {
703                 $ordering = '`commented`';
704                 $order_mode = 'commented';
705         }
706
707         $sql_order = "$sql_table.$ordering";
708
709         if (x($_GET, 'offset')) {
710                 $sql_range = sprintf(" AND $sql_order <= '%s'", DBA::escape($_GET['offset']));
711         } else {
712                 $sql_range = '';
713         }
714
715         $pager_sql = networkPager($a, $update);
716
717         $last_date = '';
718
719         switch ($order_mode) {
720                 case 'received':
721                         if ($last_received != '') {
722                                 $last_date = $last_received;
723                                 $sql_range .= sprintf(" AND $sql_table.`received` < '%s'", DBA::escape($last_received));
724                                 $a->set_pager_page(1);
725                                 $pager_sql = sprintf(" LIMIT %d, %d ", intval($a->pager['start']), intval($a->pager['itemspage']));
726                         }
727                         break;
728                 case 'commented':
729                         if ($last_commented != '') {
730                                 $last_date = $last_commented;
731                                 $sql_range .= sprintf(" AND $sql_table.`commented` < '%s'", DBA::escape($last_commented));
732                                 $a->set_pager_page(1);
733                                 $pager_sql = sprintf(" LIMIT %d, %d ", intval($a->pager['start']), intval($a->pager['itemspage']));
734                         }
735                         break;
736                 case 'created':
737                         if ($last_created != '') {
738                                 $last_date = $last_created;
739                                 $sql_range .= sprintf(" AND $sql_table.`created` < '%s'", DBA::escape($last_created));
740                                 $a->set_pager_page(1);
741                                 $pager_sql = sprintf(" LIMIT %d, %d ", intval($a->pager['start']), intval($a->pager['itemspage']));
742                         }
743                         break;
744                 case 'id':
745                         if (($last_id > 0) && ($sql_table == '`thread`')) {
746                                 $sql_range .= sprintf(" AND $sql_table.`iid` < '%s'", DBA::escape($last_id));
747                                 $a->set_pager_page(1);
748                                 $pager_sql = sprintf(" LIMIT %d, %d ", intval($a->pager['start']), intval($a->pager['itemspage']));
749                         }
750                         break;
751         }
752
753         // Fetch a page full of parent items for this page
754         if ($update) {
755                 if (!empty($parent)) {
756                         // Load only a single thread
757                         $sql_extra4 = "`item`.`id` = ".intval($parent);
758                 } else {
759                         // Load all unseen items
760                         $sql_extra4 = "`item`.`unseen`";
761                         if (Config::get("system", "like_no_comment")) {
762                                 $sql_extra4 .= " AND `item`.`gravity` IN (" . GRAVITY_PARENT . "," . GRAVITY_COMMENT . ")";
763                         }
764                         if ($order === 'post') {
765                                 // Only show toplevel posts when updating posts in this order mode
766                                 $sql_extra4 .= " AND `item`.`id` = `item`.`parent`";
767                         }
768                 }
769
770                 $r = q("SELECT `item`.`parent-uri` AS `uri`, `item`.`parent` AS `item_id`, $sql_order AS `order_date`
771                         FROM `item` $sql_post_table
772                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
773                                 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
774                                 AND (`item`.`gravity` != %d
775                                         OR `contact`.`uid` = `item`.`uid` AND `contact`.`self`
776                                         OR `contact`.`rel` IN (%d, %d) AND NOT `contact`.`readonly`)
777                         LEFT JOIN `user-item` ON `user-item`.`iid` = `item`.`id` AND `user-item`.`uid` = %d
778                         WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`deleted`
779                         AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
780                         AND NOT `item`.`moderated` AND $sql_extra4
781                         $sql_extra3 $sql_extra $sql_range $sql_nets
782                         ORDER BY `order_date` DESC LIMIT 100",
783                         intval(GRAVITY_PARENT),
784                         intval(Contact::SHARING),
785                         intval(Contact::FRIEND),
786                         intval(local_user()),
787                         intval(local_user())
788                 );
789         } else {
790                 $r = q("SELECT `item`.`uri`, `thread`.`iid` AS `item_id`, $sql_order AS `order_date`
791                         FROM `thread` $sql_post_table
792                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `thread`.`contact-id`
793                                 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
794                         STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
795                                 AND (`item`.`gravity` != %d
796                                         OR `contact`.`uid` = `item`.`uid` AND `contact`.`self`
797                                         OR `contact`.`rel` IN (%d, %d) AND NOT `contact`.`readonly`)
798                         LEFT JOIN `user-item` ON `user-item`.`iid` = `item`.`id` AND `user-item`.`uid` = %d
799                         WHERE `thread`.`uid` = %d AND `thread`.`visible` AND NOT `thread`.`deleted`
800                         AND NOT `thread`.`moderated`
801                         AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
802                         $sql_extra2 $sql_extra3 $sql_range $sql_extra $sql_nets
803                         ORDER BY `order_date` DESC $pager_sql",
804                         intval(GRAVITY_PARENT),
805                         intval(Contact::SHARING),
806                         intval(Contact::FRIEND),
807                         intval(local_user()),
808                         intval(local_user())
809                 );
810         }
811
812         // Only show it when unfiltered (no groups, no networks, ...)
813         if (in_array($nets, ['', Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]) && (strlen($sql_extra . $sql_extra2 . $sql_extra3) == 0)) {
814                 if (DBA::isResult($r)) {
815                         $top_limit = current($r)['order_date'];
816                         $bottom_limit = end($r)['order_date'];
817                         if (empty($_SESSION['network_last_top_limit']) || ($_SESSION['network_last_top_limit'] < $top_limit)) {
818                                 $_SESSION['network_last_top_limit'] = $top_limit;
819                         }
820                 } else {
821                         $top_limit = $bottom_limit = DateTimeFormat::utcNow();
822                 }
823
824                 // When checking for updates we need to fetch from the newest date to the newest date before
825                 // Only do this, when the last stored date isn't too long ago (10 times the update interval)
826                 $browser_update = PConfig::get(local_user(), 'system', 'update_interval', 40000) / 1000;
827
828                 if (($browser_update > 0) && $update && !empty($_SESSION['network_last_date']) &&
829                         (($bottom_limit < $_SESSION['network_last_date']) || ($top_limit == $bottom_limit)) &&
830                         ((time() - $_SESSION['network_last_date_timestamp']) < ($browser_update * 10))) {
831                         $bottom_limit = $_SESSION['network_last_date'];
832                 }
833                 $_SESSION['network_last_date'] = defaults($_SESSION, 'network_last_top_limit', $top_limit);
834                 $_SESSION['network_last_date_timestamp'] = time();
835
836                 if ($last_date > $top_limit) {
837                         $top_limit = $last_date;
838                 } elseif ($a->pager['page'] == 1) {
839                         // Highest possible top limit when we are on the first page
840                         $top_limit = DateTimeFormat::utcNow();
841                 }
842
843                 $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`
844                         STRAIGHT_JOIN (SELECT `oid` FROM `term` WHERE `term` IN
845                                 (SELECT SUBSTR(`term`, 2) FROM `search` WHERE `uid` = ? AND `term` LIKE '#%') AND `otype` = ? AND `type` = ? AND `uid` = 0) AS `term`
846                         ON `item`.`id` = `term`.`oid`
847                         STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = `item`.`author-id`
848                         WHERE `item`.`uid` = 0 AND `item`.$ordering < ? AND `item`.$ordering > ?
849                                 AND NOT `author`.`hidden` AND NOT `author`.`blocked`" . $sql_tag_nets,
850                         local_user(), TERM_OBJ_POST, TERM_HASHTAG,
851                         $top_limit, $bottom_limit);
852
853                 $data = DBA::toArray($items);
854
855                 if (count($data) > 0) {
856                         $tag_top_limit = current($data)['order_date'];
857                         if ($_SESSION['network_last_date'] < $tag_top_limit) {
858                                 $_SESSION['network_last_date'] = $tag_top_limit;
859                         }
860
861                         logger('Tagged items: ' . count($data) . ' - ' . $bottom_limit . ' - ' . $top_limit . ' - ' . local_user().' - '.(int)$update);
862                         $s = [];
863                         foreach ($r as $item) {
864                                 $s[$item['uri']] = $item;
865                         }
866                         foreach ($data as $item) {
867                                 // Don't show hash tag posts from blocked or ignored contacts
868                                 $condition = ["`nurl` = ? AND `uid` = ? AND (`blocked` OR `readonly`)",
869                                         normalise_link($item['author-link']), local_user()];
870                                 if (!DBA::exists('contact', $condition)) {
871                                         $s[$item['uri']] = $item;
872                                 }
873                         }
874                         $r = $s;
875                 }
876         }
877
878         $parents_str = '';
879         $date_offset = '';
880
881         $items = $r;
882
883         if (DBA::isResult($items)) {
884                 $parents_arr = [];
885
886                 foreach ($items as $item) {
887                         if ($date_offset < $item['order_date']) {
888                                 $date_offset = $item['order_date'];
889                         }
890                         if (!in_array($item['item_id'], $parents_arr) && ($item['item_id'] > 0)) {
891                                 $parents_arr[] = $item['item_id'];
892                         }
893                 }
894                 $parents_str = implode(', ', $parents_arr);
895         }
896
897         if (x($_GET, 'offset')) {
898                 $date_offset = $_GET['offset'];
899         }
900
901         $a->page_offset = $date_offset;
902
903         // We aren't going to try and figure out at the item, group, and page
904         // level which items you've seen and which you haven't. If you're looking
905         // at the top level network page just mark everything seen.
906
907         if (!$gid && !$cid && !$star) {
908                 $condition = ['unseen' => true, 'uid' => local_user()];
909                 networkSetSeen($condition);
910         } elseif ($parents_str) {
911                 $condition = ["`uid` = ? AND `unseen` AND `parent` IN (" . DBA::escape($parents_str) . ")", local_user()];
912                 networkSetSeen($condition);
913         }
914
915
916         $mode = 'network';
917         $o .= networkConversation($a, $items, $mode, $update, $ordering);
918
919         return $o;
920 }
921
922 /**
923  * @brief Get the network tabs menu
924  *
925  * @param App $a The global App
926  * @return string Html of the networktab
927  */
928 function network_tabs(App $a)
929 {
930         // item filter tabs
931         /// @TODO fix this logic, reduce duplication
932         /// $a->page['content'] .= '<div class="tabs-wrapper">';
933         list($no_active, $all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active) = network_query_get_sel_tab($a);
934
935         // if no tabs are selected, defaults to comments
936         if ($no_active == 'active') {
937                 $all_active = 'active';
938         }
939
940         $cmd = $a->cmd;
941
942         // tabs
943         $tabs = [
944                 [
945                         'label' => L10n::t('Commented Order'),
946                         'url'   => str_replace('/new', '', $cmd) . '?f=&order=comment' . ((x($_GET,'cid')) ? '&cid=' . $_GET['cid'] : ''),
947                         'sel'   => $all_active,
948                         'title' => L10n::t('Sort by Comment Date'),
949                         'id'    => 'commented-order-tab',
950                         'accesskey' => 'e',
951                 ],
952                 [
953                         'label' => L10n::t('Posted Order'),
954                         'url'   => str_replace('/new', '', $cmd) . '?f=&order=post' . ((x($_GET,'cid')) ? '&cid=' . $_GET['cid'] : ''),
955                         'sel'   => $postord_active,
956                         'title' => L10n::t('Sort by Post Date'),
957                         'id'    => 'posted-order-tab',
958                         'accesskey' => 't',
959                 ],
960         ];
961
962         if (Feature::isEnabled(local_user(), 'personal_tab')) {
963                 $tabs[] = [
964                         'label' => L10n::t('Personal'),
965                         'url'   => str_replace('/new', '', $cmd) . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : '/?f=') . '&conv=1',
966                         'sel'   => $conv_active,
967                         'title' => L10n::t('Posts that mention or involve you'),
968                         'id'    => 'personal-tab',
969                         'accesskey' => 'r',
970                 ];
971         }
972
973         if (Feature::isEnabled(local_user(), 'new_tab')) {
974                 $tabs[] = [
975                         'label' => L10n::t('New'),
976                         'url'   => 'network/new' . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : ''),
977                         'sel'   => $new_active,
978                         'title' => L10n::t('Activity Stream - by date'),
979                         'id'    => 'activitiy-by-date-tab',
980                         'accesskey' => 'w',
981                 ];
982         }
983
984         if (Feature::isEnabled(local_user(), 'link_tab')) {
985                 $tabs[] = [
986                         'label' => L10n::t('Shared Links'),
987                         'url'   => str_replace('/new', '', $cmd) . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : '/?f=') . '&bmark=1',
988                         'sel'   => $bookmarked_active,
989                         'title' => L10n::t('Interesting Links'),
990                         'id'    => 'shared-links-tab',
991                         'accesskey' => 'b',
992                 ];
993         }
994
995         if (Feature::isEnabled(local_user(), 'star_posts')) {
996                 $tabs[] = [
997                         'label' => L10n::t('Starred'),
998                         'url'   => str_replace('/new', '', $cmd) . ((x($_GET,'cid')) ? '/?f=&cid=' . $_GET['cid'] : '/?f=') . '&star=1',
999                         'sel'   => $starred_active,
1000                         'title' => L10n::t('Favourite Posts'),
1001                         'id'    => 'starred-posts-tab',
1002                         'accesskey' => 'm',
1003                 ];
1004         }
1005
1006         // save selected tab, but only if not in file mode
1007         if (!x($_GET, 'file')) {
1008                 PConfig::set(local_user(), 'network.view', 'tab.selected', [
1009                         $all_active, $postord_active, $conv_active, $new_active, $starred_active, $bookmarked_active
1010                 ]);
1011         }
1012
1013         $arr = ['tabs' => $tabs];
1014         Addon::callHooks('network_tabs', $arr);
1015
1016         $tpl = get_markup_template('common_tabs.tpl');
1017
1018         return replace_macros($tpl, ['$tabs' => $arr['tabs']]);
1019
1020         // --- end item filter tabs
1021 }