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