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