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