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