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