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