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