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