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