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