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