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