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