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